С++ или Javascript? [закрыт]
Хотите улучшить этот вопрос? Переформулируйте вопрос так, чтобы на него можно было дать ответ, основанный на фактах и цитатах.
Закрыт 7 лет назад .
Здравствуйте. Недавно я начал поверхностное изучение JS. Здесь я задал вопрос о нем, но мне сказали, что лучше заняться С++. Скажите, что практичнее, легче, даёт больше возможностей? Насколько я знаю, JS не требует ничего, а С++ требует компилятор. Если не сложно, посоветуйте вместе с аргументами и ссылками. Буду очень признателен.
Аргументы? Сложно даже представить, с чего начать. Думаю, начинать вам надо с целей. Они имеют совершенно разные, почти непересекающиеся применения. Определитесь, чего вы хотите для начала.
C++ несомненно хорош для обучения программированию, так как даёт возможность понять, как работает компьютер и как работают программы. Пощупать алгоритмы и т.п. В этом смысле, JavaScript плохо подходит. Вероятнее всего, если вы будете с него начинать, то если у вас нет больших талантов и/или сильной целеустремлённости, то ничего хорошего из этого не выйдет.
Вообще, странное противопоставление. Это два разных языка, созданных для совершенно разных целей и имеющие совершенно разное предназначение. Если Вы только начинаете изучать программирование, то лучше, конечно, начать не с JS, поскольку это довольно узконаправленный язык. Лучше С++ или даже С, поскольку он проще и короче. Это языки общего назначения, JS в основном используется для веб-программирования. Применение его для других целей экзотика.
Для С/С++ нужен компилятор. Какой лучше выбрать здесь уже обсуждалось неоднократно. Но повторюсь. Для начинающий лучше, на мой взгляд, среда разработки Dev-C++. Простенькая, бесплатная, но довольно мощная. Использует компилятор gcc.
Сравнение C# и JavaScript. Основы

Мой более-менее серьезный путь в программировании начался с написания программ на языке C#, иногда я пробовал писать на JavaScript, и то и дело впадал в ступор в таких ситуациях, когда неверно указывал имя переменной и узнавал об этом спустя много много лет час отладки, так как со мной рядом не было моего компилятора, который бы меня выручил в трудную минуту. Через некоторое время, помимо C# я начал писать много кода на JavaScript и в настоящее время могу делать это без особых трудностей, меня больше не смущает неявное приведение типов и динамическая типизация.
В данной статье я бы хотел систематизировать свои базовые знания об этих языках и рассмотреть их сходства и различия. Данная статья может служить руководством для C# разработчиков, которые хотят изучить JavaScript и наоборот. Также хочу заметить, что в данной статье описываются возможности клиентского JS, так как опыта разработки на Node.js у меня нет. Итак, если вы все ещё не потеряли интерес — приступим.
Namespace и js-модули
В каждой программе для избежания конфликтов в именах переменных, функций, классов или других объектов мы объединяем их в некоторые области. Таким образом, если две разные области будут содержать элементы с одинаковыми именами, конфликта не произойдет.
В C# для разбиения программы на части используются пространства имен. Для их объявления используется ключевое слово namespace . Например, если мы хотим создать набор компонентов пользовательского интерфейса, то логично поместить их все в одно пространство имен, например, Components . При этом принято чтобы пространство имен имело следующее именование [AssemblyName].[DirectoryName].[DirectoryName].[. ] . В каждом файле класс компонента пользовательского интерфейса необходимо поместить внутрь пространства имен:
Содержимое файла ComboBox.cs :
Для того, чтобы начать использовать компоненты необходимо импортировать их из пространства имён следующим образом using AssemblyName.Components . При данном способе подключения одной строкой мы импортируем все объекты в текущий файл.
В JS для этих же целей применяются ES-модули. При их использовании мы в какой-то степени эмулируем поведение пространств имен написанием дополнительного кода. Рассмотрим тот же пример с библиотекой компонентов. Допустим у нас есть папка Components , которая содержит компоненты пользовательского интерфейса ComboBox.js , Checkbox.js , Button.js и тд. Для того чтобы получить схожее поведение по сравнению с пространством имен в папке Components необходимо создать файл index.js , который будет содержать следующий код:
Для того, чтобы использовать данные компоненты необходимо импортировать их в текущий файл. Это можно сделать следующим образом: import * as Components from ‘./../Components’ , после ключевого слова from нам необходимо указать путь к папке, в которой находятся все описанные компоненты.
Способы объявления переменных
Ключевое слово var
Как известно C# является строго типизированным языком программирования, поэтому при объявлении переменной компилятору должен быть известен её тип, для этого обычно он указывается перед её именем.
Но мы также можем сказать компилятору, что он должен вывести тип самостоятельно из выражения, стоящего после знака присваивания. Это стало возможно благодаря введению в версии C# 3.0 ключевого слова var .
С помощью var мы можем создавать объекты анонимного типа:
В JavaScript для объявления переменных также можно использовать ключевое слово var , однако, в отличии от C# областью видимости данных переменных будет вся функция или объект window , если переменная была объявлена вне функции.
Хоть у вас и есть возможность объявлять переменные с помощью var в JavaScript, но сейчас этого делать не рекомендуется, после выхода стандарта ES6 было добавлено ключевое слово let , которое также позволяет объявлять переменные, но его преимуществом заключается в том, что их областью видимости будет являться блок, в котором они объявлены, а не вся функция.
Константы
Как в C#, так и в JavaScript для объявления константного поля используется ключевое слово const . Правда стоит отметить, что понятие константы в данном случае является различным для данных языков.
В C# константой называется выражение, которое может быть полностью вычислено на этапе компиляции, т.е. константы могут быть числами, логическими значениями, строками или нулевыми ссылками..
В JavaScript значение константы также нельзя изменять, однако нет ограничений, накладываемых на значение как в языке C#, ей можно присваивать любые значения/объекты/массивы. Однако, если в константу присвоен объект, то от изменения защищена сама константа, но не свойства внутри неё:
Ключевое слово void
Во время написания данной статьи, я экспериментировал в консоли с функциями и по првычке начал описывать функцию как в C# void SomeFunction. , и для меня было большой неожиданностью, когда я узнал, что в JavaScript есть ключевое слово void . Как оказалось void в JavaScript является унарным оператором, который вычисляет значение операнда, затем отбрасывает его и возвращает undefined .
Таким образом, можно сказать, что использование void явно указывает отсутствие возвращаемого значения, подробнее с примерами его использования вы можете ознакомиться в следующей статье статье.
В C# void не является оператором, однако по сути имеет схожее значение. Здесь он обозначает отсутствие возвращаемого значения функции:
Однако, как можно заметить в примере выше, void стоит в том месте, где обычно указывается тип возвращаемого значения, и это не случайно, ведь в C# void также является типом.
void в качестве типа может использоваться только в небезопасном контексте при работе с указателями.
Ключевое слово new
В JavaScript ключевое слово new является оператором, и используется привычным для многих C-подобных языков образом — для создания объекта.
В C# new может использоваться для следующих целей:
- для создания объектов;
- для скрытия наследуемого члена базового класса;
- чтобы ограничить типы, которые могут использоваться в качестве аргументов для параметра типа в универсальном классе.
Первый случай аналогичен применению new в JavaScript.
Основные типы данных
В каждом языке имеются типы данных — примитивы, на основе которых строятся другие типы данных, давайте рассмотрим типы данных предоставляемые нам в C# и JavaScript.
Примитивные типы С#:
- Целочисленный со знаком: sbyte , short , int , long
- Целочисленный без знака: byte , ushort , uint , ulong
- Символы Unicode: char
- Набор символов Unicode: char
- Числа с плавающей запятой: float , double
- Десятичный с повышенной точностью: decimal
- Логическое значение: bool
Базовый классом является Object .
Примитивные типы данных:
- Число number
- Строка string
- Логический тип boolean
- Специальное значение null
- Специальное значение undefined
Базовым типом является Object .
После изучения примитивов обоих языков можно придти к следующим выводам:
- Вместо достаточно большого набора числовых типов в JavaScript имеется единственный тип number ;
- В JavaScript отсутствует тип char , вместо него стоит использовать тип string ;
- В обоих языках базовым типом является Object ;
- Отличительной особенностью JS является то, что null и undefined выделены в отдельные типы, в то время как в C# null — это ключевое слово обозначающее отсутствие значения.
- В JS присутствует тип symbol , который используется в основном внутри самого стандарта JavaScript, для того чтобы иметь возможность добавлять новый функционал без конфликта с существующей кодовой базой.
Как правило, сейчас все больше приложений, в которых необходимо выполнять обработку данных на клиенте, для чего требуется большая точность в вычислениях. В настоящее время в JavaScript отсутствует встроенная возможность работы с большими числами, однако в недалеком будущем планируется добавить новый тип BigInt . Для решения аналогичных задач в C# имеется класс System.Numerics.BigInteger .
Проверка типа объекта
Проверка типа является достаточной типичной операцией для большинства языков программирования. Основываясь на типе, мы можем выполнять различные действия. Например, рассмотрим пример из жизни: вы слышите звонок в дверь, если к вам пришел пьяный сосед (объект с типом Пьяный Сосед) чтобы занять денег, то вы вряд ли откроете ему дверь, но если за дверью ваш лучший друг (объект с типом лучший друг), то вы не задумываясь впустите его в квартиру. C# и JavaScript также предоставляют средства для проверки типа объектов.
Оператор typeof
Для получения информации о типе как в C#, так и в JavaScript имеется оператор typeof . Давайте рассмотрим принцип его работы в обоих языках:
В С# оператор typeof применяется к типу и возвращает объект класса Type , который содержит всю информацию о типе.
В JS typeof возвращает строку, указывающую тип операнда.
В примере выше можно заметить некоторые особенности работы данного оператора. Кажется логичным, если выражение typeof new Animal() возвращало бы строку ‘Animal’ , a typeof [1,2,3] — строку Array , однако как бы ни было парадоксально, результатом в обоих случаях является ‘object’ . Также в связи с тем, что классы в JS являются оберткой над функциями, то выражение typeof class C <> вернет ‘function’ вместо ‘class’ . Ещё одним интересным фактом является то, что выражение typeof null вернёт ‘object’ . В JavaScript данный оператор имеет большой недостаток: все не примитивные объекты для него на одно лицо, все они имеют один тип object .
Стоит заметить, что в JavaScript typeof можно применять к чему угодно: объектам, функциям, классам и т.д… В C# данный оператор применяется лишь к типам.
is и instanceof
Помимо получения информации о типе, порой бывает полезно проверить принадлежность объекта к определенному типу.
В C# для данных целей имеется оператора is .
В JavaScript для того, чтобы выяснить к какому типу принадлежит объект необходимо использовать оператор — instanceof .
Логические значения и проверка на null
Практически повсеместно, для того чтобы не получить Null reference exception , перед использованием переменной мы проверяем её на null , а в случае с JavaScript, ещё и на undefined .
В C# мы постоянно видим подобный код:
В JavaScript данную конструкцию можно записать несколько короче. Связано это с тем, что в отличии от C#, в JavaScript множество значений кроме false при приведении типов также расцениваются как false :
- null
- undefined
- «» (пустая строка)
- 0
- NaN (not a number)
Таким образом, приведенный выше код на C# можно записать следующим образом:
В связи с тем, что проверки на null происходят повсеместно, в C# 6.0 был добавлен Null Propagation Operator .? .
С его помощью данный участок кода можно переписать следующим образом:
В JavaScript обычно делают следующим образом:
Установка значений по-умолчанию
Ещё одной частой операцией является установка значений по-умолчанию, с версии 2.0 в C# появился Null Coalescing Operator — ?? .
Следующие две строки кода на C# являются эквивалентными:
В JavaScript подобную операцию обычно делают следующим образом.
Однако мы можем применять операторы && и || только в том случае, если 0 , false и пустая строка не являются допустимыми значениями.
В обозримом будущем операторы ?. , ?? должны появиться и в JavaScript (в настоящее время они прошли стадию Stage0), подробнее об этих операторах в JavaScript можно прочитать в статье.
Ключевое слово this
Как в C#, так и в JavaScript имеется ключевое слово this . Обычно в C# понимание предназначения this не вызывает никакого труда, однако в JavaScript это является одной из самых сложных концепций языка. Далее рассмотрим применение this на примерах.
В C# ключевое слово this указывает на текущий экземпляр класса.
В данном примере в выражении Console.WriteLine(this.name) , this указывает на переменную employee .
Так как this — текущий экземпляр класса, то его нельзя использовать в методах не привязанных к определенному типу, например в статических методах.
В JavaScript значение this называется контекстом вызова и будет определено в момент вызова функции. Если одну и ту же функцию запускать в контексте разных объектов, она будет получать разный this :
К тому же, в JavaScript присутствует возможность явного указания значения this с помощью функций: call , bind , apply . Например, вышеприведенный пример можно переписать следующим образом:
Деструктуризация
Часто бывает необходимо присвоить несколько полей объекта локальным переменным. Например, как часто вы наблюдаете подобный код?
Для подобных целей можно использовать деструктуризацию. Данную возможность в разной степени поддерживают оба языка.
В C# 7.0 для поддержки деструктуризации появился новый вид функций, называемый деконструкторами. Для того чтобы объявить деконструктор нам необходимо определить метод с именем Deconstruct , все параметры которого должны быть объявлены с модификатором out :
Поддержка деструктуризации или (destructuring assignment) в JavaScript появилась в шестом стандарте EcmaScript. С её помощь. можно присвоить массив или объект сразу нескольким переменным, разбив его на части.
Стоит отметить, что деструктуризация в JavaScript имеет больше возможностей, чем в C#:
- Изменение порядка переменных;
- Отсутствие необходимости явного объявления деконструкторов;
- Поддержка деструктуризации массивов;
- Установки значений по-умолчанию;
- Присваивание свойств объекта в переменную с другим именем;
- Поддержка вложенной деструктуризации.
Заключение
В данной статье мы обсудили лишь самые основные концепции языков C# и JavaScript. Но остались не затронуты ещё многие аспекты:
- коллекции
- функции
- классы
- многопоточность
Каждая из этих тем является достаточно обширной и будет раскрыта в дальнейшем в отдельной статье.
C# vs JavaScript: Which Programming Language Is better For Your Needs?
Michał is a highly skilled Business Development Manager with a passion for the intersection of medical technology and cutting-edge technology. When he’s not working, Michał can often be found enjoying a good movie or hitting the trails for a hike.
Which technology should one choose for their business project: C sharp vs JavaScript?
There are differences between the two programming languages. Any educated programmer knows that not all programming languages are created in the same way or can even be used for the same purpose. When we talk about C# and JavaScript, the differences between the two computer languages are huge. However, these two programming languages have several places where they overlap.
Curious? Let’s deal with this.
What is C#?
Initially, Microsoft was going to release its own version of the Java language (Microsoft Java or J++), but they had to sue the copyright holders (Sun Microsystems) because of some controversial points. Therefore, the management decided on the need to create their own language that would meet their requirements and the development of which they could control. This is how C# came to be.
C# was developed thanks to the efforts of Anders Hejlsberg, the creator of the compiler that formed the basis for Turbo Pascal and the Delphi programming language. The first version of the language was released in June 2000 (it is possible that Microsoft wanted to celebrate the new millennium), and the final version was released in 2002 along with Visual Studio. Now C# has become one of the most popular programming languages, even slightly ahead of its predecessor.
It is difficult to talk about any philosophy of the language when it comes to C#. The fact is that from the very beginning, the language was not open source because it was created specifically for one well-known corporation headed by Comrade Gates. Many concepts and constructions were borrowed from other languages, such as C, C++, Java, etc. (the first versions of the language were very similar to Java, although now C# can no longer be considered just a clone of this language, it has gone so far ahead).
C# cannot be considered only as a language. It is part of a large system that includes the Windows OS, the Visual Studio development environment (and other tools), and, of course, Microsoft itself, which provides support for this language. C# will exist and develop as long as Microsoft exists and as long as people use Windows, and this will be a very, very long time.
The early versions of C# were somewhat straightforward and were designed to run crude commands with a task-oriented approach. Tell the computer a simple request, and the computer will complete the task. This is more or less the main function of any programming language. C# stands out for being exclusive to Microsoft software or other Microsoft products.
To be clear, C# was a proposed JavaScript alternative that could be used exclusively for Microsoft software. Since C# is the programming language of the most popular software on the planet, it has gone through many versions and updates. C# is considered a general-purpose programming language that can be used for a variety of purposes. Even modern nifty updated versions of C# are component, object, and task-oriented. However, most programmers enjoy using C# because of its simplicity.
Eager to find more languages to compare with С Sharp? Check out Ruby on Rails vs C# — Which Technology Should You Choose?
What is JavaScript?
JavaScript is one of the most popular programming languages in the world, with over twenty years of history. It is also one of the three main languages for web developers:
- HTML: Lets you add content to your web page.
- CSS: Sets the styles and appearance of the web page.
- JavaScript: Improves the behavior of the web page.
JavaScript can be quickly learned and easily used for a wide variety of use cases, from simple site improvements to running games and web applications. Or better yet, there are thousands of JavaScript templates and apps available thanks to free sites like GitHub.
JavaScript was created in 10 days by author Brandan Eich, who worked for Netscape back in 1995. It was originally called Mocha. The name of the language was changed to Mona and then to LiveScript until it finally became JavaScript. The original version of the language was limited only to the Netscape browser and offered narrow functionality, but over time it continued to evolve in part thanks to the community of developers who kept working on it.
In 1996, JavaScript was standardized and given the official name ECMAScript, with ECMAScript 2 released in 1998 and ECMAScript 3 the following 1999. This has translated into today’s JavaScript, which now works not only across browsers but also across multiple devices, including mobile and desktop computers.
JavaScript has continued to grow since then, with 92% of sites using it in 2016. In just twenty years, it has grown from a primitive programming language to one of the most popular tools in a web developer’s arsenal. If you use the Internet, then you have certainly come across JavaScript.
Interestingly, JavaScript was always meant to support the Internet, even when the Internet in the mid-1990s consisted mostly of dial-up and very limited browsing. JavaScript is used today to build websites and help run larger platforms like Netflix and Hulu.
However, most programmers take JavaScript with some fear. Although the coding language itself is complex, it also has many nuances and is not as generally used as C# or even C++. JavaScript is not as useful as developers might imagine. However, for web projects, there is a chance that JavaScript will be the programming language that needs to be used, so most devs know this language by heart.
Why should we compare them?
There are times when C# and JavaScript overlap, and not just in the sense that both might need to be used for the same client or project. JavaScript can and does run concurrently with C#, both from an application perspective and from a coding perspective.
Even in those rare cases where JavaScript is used outside of building web frameworks, it is unlikely that this code will do anything other than support C#.
In general, there is not much in common between C# and JavaScript. But there are many differences.
Some might think that C# and JavaScript are as different as day and night. But the simple truth is that both of these coding languages are opposite sides of the same coin. Although both languages were developed during the same time period, the fact is that C# and JavaScript have huge differences that constantly expose them to competitors.
Let’s go through the main areas to compare C# vs JavaScript.
Speed of coding/easiness of coding
Unfortunately, using JavaScript is tedious. When the encoder uses JavaScript, there is no additional support in the program to help code faster. C# is the exact opposite, especially with newer versions, including autocomplete and dynamic typing to help catch errors and speed up coding. C# lets you do more, faster, with fewer bugs.
Winner: C#
Performance
C# and JavaScript are languages, so they don’t have any specific performance characteristics by themselves. C# is compiled to .NET IL and executed in a virtual machine, and various optimizations (like the JITing) can be involved. JavaScript is not compiled but interpreted — and executed by a browser-specific JavaScript engine. Each browser can take different approaches to improve the «performance» of JavaScript execution, but performance optimization usually involves a trade-off (for example, between speed and memory).
While everything else is equal (and non-trivial), .NET code — JIT or not — will perform better than similar JavaScript code running in the browser. The degree of performance difference is highly dependent on the specific program. Everything from the size and number of objects processed to how and when you use loops will affect how one runtime compares to another.
However, if you hire a seasoned C# developer and a beginner JavaScript developer, your C# will certainly be faster. If you have one that is good at both, then your C# will probably be faster, but the difference may not be as big as you thought — this is all very program-specific.
Draw
Stability
At this point, it’s no surprise that C# is a more consistent and flexible coding language in between. This is mainly due to the automatic error detection associated with C# programming. However, C# also has fewer runtime errors than JavaScript, and it can also be used in more ways than JavaScript.
Winner: C#
Popularity
C# is definitely in demand today. There are a lot of vacancies, both for large enterprise projects with a conservative stack and for companies starting new projects, where the most advanced developments and tools are used.
At the same time, it is very important to understand that the scope of this language is very wide:
- development of REST API and web services — ASP.NET MVC, ASP.NET Web API;
- game development — Unity;
- mobile app development — Xamarin;
- development of desktop applications — WPF, Windows Forms;
- development of cross-platform applications and services — .NET Core, Mono;
- development of cloud services — for C#, there are SDKs from all major cloud platforms;
- developing stored procedures for SQL Server.
Therefore, within the framework of one language, it is possible to combine specialization in several areas and at the same time use familiar tools and libraries.
Talking about exact numbers, according to Google Trends , JS has a confident lead from the pursuer.
On top of that, we can assume that C# is losing popularity in cloud applications but still plays an important role in games.
A new survey of developers from Slashdata showed that the popularity of C# fell from third to sixth place in three years. C# is the primary language of the Microsoft .NET platform.
However, despite the decline in popularity, the general use of C# is still growing, and it is especially popular in game development.
The British company Slashdata conducted a survey in which more than 30,000 software developers from more than 160 countries took part. They surveyed over 17,000 developers around the world for this report, entitled The State of the Developer Nation.
This is the 19th year that a research company has conducted such a study.
Slashdata report differs from other «popularity» indexes such as StackOverflow or Redmonk. This is because Slashdata researchers aim to measure the absolute number of users of a programming language, not just determine the relative popularity of each programming language.
The Slashdata report lists several important findings regarding programming languages.
First, JavaScript is by far the most popular programming language, with 12.4 million developers worldwide using it. Python now has 9 million users after adding 2.2 million new developers in the last year alone, surpassing Java in early 2020.
The report notes that C# is still gaining popularity, but not as quickly as some other languages.
«Perhaps C# continues to dominate the game developer and AR / VR ecosystems,» the report said. Additionally, the report noted that C# appears to be losing ground in desktop development. Perhaps this was due to the emergence of cross-platform tools based on web technologies, according to researchers at Slashdata.
Winner: JS
Community
Meanwhile, due in part to its flaws, the Javascript ecosystem has become vast and egalitarian. In fact, this is one of those things that people complain about when they don’t realize that this is not really one community. These are a dozen different ones that sprang up very quickly (even jQuery’s grandfather is just over 10 years old) and is still in the process of being cross-pollinated and refined into their own stuff.
The Javascript community has come up with ingenious solutions to important problems. And more importantly, there are several different solutions for all tastes and different use cases. Some can even be used at the same time. So we have:
- Babel, Typescript, Purescript, and before that Coffeescript, competing for people who want nicer syntax (and as a result, help guide the evolution of the language).
- Typescript, Flow, and Eslint to catch errors before running the application.
- KnockoutJs, AngularJs, BaconJs, and Redux for state management
- AngularJs, EmberJs, virtual systems like React, Backbone, and web components to create templates and components
- Mocha, Jest, Jasmine, Qunit for unit testing
- although Node is the leader on the server, it also had its predecessors in Rhino, JScript, and others.
All this and much more. It is the most successful community of programmers of all time. Definitely the worst language, but many times larger, more diverse, bolder, and fast-paced community.
Winner: JS
Talent pool
Rolling back to Slashdata’s report, they found that only 6.0 million developers were using C#. This represents a serious blunder for the language: it fell from 3rd to 6th place in the poll. Moreover, C# even gave way to PHP, which had 6.1 million users.
Given the fact that Microsoft is actively developing the .NET Core platform, we think that the number of vacancies in this direction will increase in the near future. The market, according to the classic version of .NET, has already been formed, and most likely, there will not be any global changes in it in the near future. One should not expect a big rise or fall in wages. But don’t forget that C# is one of the top ten «highest-paid» programming languages.
According to Developer Economics , there were 12.4 million software developers using JavaScript in the third quarter of 2020. This means that 53% of all developers in the world have used JS at some point.
According to a 2020 Stack Overflow Developer Survey , «JavaScript is the most used programming language on earth. Even Back-end developers will use it more often than any other language. «Meanwhile, the latest data provided by Slashdata showed that there were 10.7 million JavaScript software developers globally in 2018 ( source ).
Winner: JS
Easiness to learn
JavaScript is a dynamically typed programming language, which means it doesn’t need to be changed to keep the same variable in two places. C#, on the other hand, is a statically typed coding language, which means that each variable must be changed independently. Some say this makes C# a simpler language in between, especially because C# encounters fewer coding errors at runtime than JavaScript.
In terms of training, the requirements for newbies have increased in recent years. It’s well worth learning JavaScript — it’s still the most easily accessible area of web programming for newbies. However, it will not be possible to find a job having bare theory.
Of course, we would advise beginners to learn C#. In our opinion, this is a perfectly balanced OOP language that makes it easy enough to start working with it, using simple and concise constructions at the beginning, and in the future, gradually move to such powerful tools as Linq and lambda expressions.
A person who starts learning programming with this language will initially acquire the correct skills when writing code.
In this regard, C# has a number of advantages:
- It is a strongly typed language, which means that it is much easier for a programmer who starts their training in this language to understand what a data type is and what data types there are. This compares favorably with Python and JavaScript.
- It is a .NET language, which means that the programmer will be working in the managed CLR and will not have to deal with memory allocation and memory deallocation. They will be able to focus directly on solving algorithmic and business problems without being distracted by finding the causes of memory leaks and sudden exceptions.
- It is a C-like language (which is obvious from its name). Its syntax is much sleeker and more concise than Pascal, which has long been the main language used for teaching programming. At the same time, a person familiar with one C-like language can easily understand and read the code of other languages of this family.
Winner: C#
Error detection
This distinction is probably the most obvious to programmers, mainly because it can be the most frustrating. The distinction is very simple: JavaScript cannot detect errors until coding is complete and the program is executed, whereas, in C#, you can detect an error in your code and change it at any time. For this purpose, JavaScript is often a source of constant frustration because it forces the programmer to go through the entire code to find the error after everything else has been completed, which means changing any variables associated with the code until the program is running smoothly. There is no such problem in C#.
Winner: C#
Service
Maintaining code is of great importance to programmers and is directly related to the simplicity of the typed language that each code uses. Because JavaScript is dynamically typed, code maintenance is usually a hassle, as all the code must be pulled and examined to update or fix bugs. On the other hand, statically typed C# code is easy to maintain, just as it is easy to find and fix bugs.
Winner: C#
Syntax
JavaScript runs on HTML-based syntax, and as such, the syntax is more complex and requires higher maintenance. C# operates in a concise command syntax that is easier to use and easier to learn. The syntax is important to coders in the sense that it is easier to talk frankly about something than beat around the bush. JavaScript requires coders to overcome several difficulties, whereas C# allows coders to write using a simple syntax.
Winner: C#
Cost of development
All projects are individual. Hence, we can’t say in advance how much you will have to spend. The final quote would be impacted by a number of requirements and the client’s wishes.
Still, we can give you a clearer understanding of what to expect by looking at the rating of » What Languages Are Associated with the Highest Salaries Worldwide. «
As per this data, C# devs earn $57k, while Javascript Developers get $53k. Thus, we can see that wages are approximately of the same meaning.
Draw
Pros and Cons
JS pros
JavaScript is a language with great advantages that make it the best choice among its kind, especially in some use cases. Just a few advantages of using JavaScript:
- You don’t need a compiler because the web browser interprets it;
- It is easier to learn than some other programming languages;
- Errors are easier to identify and therefore correct;
- It can bind to special page elements or events like click or mouseover;
- JS works in different browsers and on different platforms;
- You can use JavaScript to validate input data and reduce the need for manual data validation;
- It makes the site more interactive and attractive to visitors.
JS cons
Each programming language has its flaws and weaknesses. One of the reasons for the problems is the popularity of the language. When a programming language becomes as popular as JavaScript, it becomes a target of increased interest for hackers, scammers, and other malicious third-party manifestations that try to find vulnerabilities and security vulnerabilities. Some weak points include:
- Vulnerable to exploits (malicious code that exploits software product vulnerabilities);
- Can be used to run malicious code on the user’s computer;
- Not always supported by some browsers or devices;
- Chunks of JS code can be very large;
C# pros
- Microsoft support. Unlike Java, which did not benefit from Oracle’s takeover, C# is doing well thanks to Microsoft’s efforts;
- Lately, it has been improving a lot. Since C# was created later than Java and other languages, it required a lot of work. This also applies to popularization and free-of-charge feature — tools (like Visual Studio, Xamarin) became free for individuals and small companies;
- A lot of syntactic sugar. Syntactic sugar is a construct that is designed to make it easier to write and understand code (especially if it is another programmer’s code) and do not play a role in compilation;
- Average entry threshold. Syntax similar to C, C++, or Java makes the transition easier for other programmers. For beginners, it is also one of the most promising languages to learn;
- Xamarin. With Xamarin in C#, you can now write for Android and iOS. This is undoubtedly a big plus since their own mobile OS (Windows Phone) has not gained much popularity;
- A large community of programmers;
- Many vacancies for the position of C# programmer in any region.
C# cons
- Bad GUI x-platform.
- C# is less flexible because it mostly depends on. NET Framework.
What is C# good for?
For a long time, C# has been confidently holding its positions in the ranking of the most demanded languages in the development market. At first, only Windows developers were interested in it, but then C# learned to work on Mac OS, Linux, iOS, and Android. And after the platform code was opened to everyone, almost all possible restrictions on the use of C# were removed. As a result, the language is actively developing and being used more and more. It is often recommended for study as one of the basic for developers of any profile.
The C# toolkit allows you to solve a wide range of problems. The language is really very powerful and versatile. It is often used to develop:
- web applications,
- games,
- mobile applications for Android or iOS,
- programs for Windows.
The list of development possibilities is practically unlimited due to the widest set of tools and facilities. Of course, all of this can be done with other languages. But some of them are highly specialized, and in some, you will have to use additional third-party tools. In C#, solving a wide range of problems is as fast, simple as possible, and with less time and resources.
Since the language belongs to Microsoft, it is used in almost all products that have been developed or purchased. Let’s consider the most interesting of them.
- Mono is a project that was dedicated to the free implementation of C# and .NET. That is, it would allow writing in C#, for example, for Linux and Mac OS X. Based on Mono, XamarinStudio was created, which allows you to create mobile applications in C# without using the native for platform languages (Java and Objective-C). It was purchased from the author (Miguel de Icaz) and implemented in Visual Studio.
- DirectX is an API for Windows programming, most often used in game programming. With DirectX, you can write, say, a great 3D shooter.
- Unity is a cross-platform game engine that allows you to create 2D and 3D games. It is very popular among indie developers, but it is also adopted by large companies. So, for example, Hearthstone is built on Unity.
What is JavaScript good for?
JavaScript is mainly used in front-end development. This language, onward with HTML and CSS, is included in the basic set of front-end tools. JavaScript is used to create client-side browser applications. They provide interactivity for sites. For instance, when a user fills out a form and clicks the Subscribe button, an instant response is usually provided by JavaScript code.
- JS is not limited to browsers and web applications. Using this language, they solve the following tasks:
- Development of native applications. For example, Android and iOS apps are built using the React Native framework.
- Server development. Node.js is used for internal development.
- Desktop applications’ development. JS is used in office suites Microsoft and OpenOffice, in Adobe applications.
- Programming of equipment and household appliances. For example, payment terminals, set-top boxes.
Summary
Although both C# and JavaScript were developed around the same time, each was designed with a specific purpose in mind. JavaScript was designed to support the web, and C# was designed to support Microsoft.
In terms of differences, C# and JavaScript have their own advantages and disadvantages. For example, JavaScript can be used on many internet platforms and is most commonly used to build web pages or support internet browsers.
Meanwhile, C# is generally considered the best program because it is easier to manage, more reliable, more productive, and more consistent, even if the language is restricted to Microsoft. When determining which programming language to use, acknowledge the specifics of each language and the tasks you need to accomplish. Internet projects require JavaScript, while software projects require C#.
Can’t decide which language to choose? Consult your product with us. We can provide you with technical consultancy and connect you with experts skilled in both technologies, matched with your product and the required industry.
JavaScript vs. C++: создание одной и той же 3D-игры на обоих языках
Я написал один и тот же шутер от первого лица на JavaScript, а потом на C++. В этой статье опишу, как все это происходило.
Несколько лет назад, когда WebGL начал свое шествие по браузерам, у меня возникла идея — написать шутер от первого лица на JavaScript и HTML. Абсолютно безумная затея, но она сработала, и даже не очень лагала (попробуйте сами). В свободное время я понемногу модифицировал код, со временем игра обросла фичами и стала интересной.
JavaScript-версия: работает в браузере
Тем временем появился Electron (если кратко, инструмент, позволяющий соединить веб-приложение с браузером и запускать как нативное приложение). И я задумался: «Опа! Может, сделать настоящее нативное приложение из моей игры на WebGL? Засуну его в Electron, и дело в шляпе».
Я так и сделал. Получилось на удивление неплохо, настоящее приложение. Но результат работал не очень: хоть я и приложил много усилий, чтобы приложение работало именно как приложение, а не веб-сайт, но все равно недостатков была масса — большие задержки, отсутствие нормальной аппаратной поддержки, 3D, настроек полноэкранного режима, плохая блокировка курсора и еще куча всего.
Поэтому я решил переписать свою игру на C++. И правда — а почему нет-то? Наверное, и не слишком сложно будет — JavaScript-код моей игры основывался на 3D-движке CopperLicht (я его сам написал), у которого API почти как у 3D-движка IrrLicht (его тоже написал я), на котором и так основан мой игровой движок Framework CopperCube. Работы вроде не очень много — нужно только переписать игровую логику. Все остальное — окно, интерфейс, коллизии, шрифты, текстуры, звук, картинки, обработка файлов и другое — уже было написано, еще и API использовало очень похожее.
На портирование ушли недели, но в результате игра стала нативным Win32-приложением на C++. Можете скачать ее здесь.
Нативная версия на C++
Сравнение
Теперь у меня есть редкая возможность сравнить ход разработки одного и того же приложения на C++ и JavaScript. Разберу по пунктам.
Производительность
Сейчас вы очень удивитесь: производительность обеих реализаций не сильно различается (прим. перев.: А вот на компьютере без дискретной видеокарты разница огромна — в браузере игра почти не играбельна, а вот в C++-версии отсутствуют даже малейшие лаги).
Даже самая ресурсоемкая часть — процедурная генерация домов и обнаружение столкновений физическим движком — не сильно лагали на JavaScript. Тормозит буквально раза в два больше, чем в C++-версии. Оптимизация выполнения JavaScript в Chrome меня очень впечатлила. К несчастью, все равно JavaScript-версия ощущается куда более медленной. Далее я объясню, почему.
Дьявол кроется в деталях
В реализации на C++ я мог контролировать любую деталь выполнения, любую мелочь. В JavaScript-версии во многих вещах я полагался на браузер — в этом и крылась проблема. На JavaScript процедурная версия едва заметно подлагивала из-за того, что некоторые вызовы WebGL имеют свойство ненадолго вешать браузер. Буквально на миллисекунды, но их очень много — поэтому игра «плыла», ощущалась очень медленной по ритму. Я написал несколько обходов для основных проблем, но с другими ничего сделать, увы, было нельзя. На C++ же контролировать можно все — и если возникают проблемы, можно придумать способ их решить.
Версия на JavaScript на моем компьютере выдавала тот же FPS, что и на C++ — около 120 кадров в секунду. Но ощущалась она очень, очень медленной. В зависимости от используемой ОС и железа компьютера браузер ведет себя сильно по-разному, и даже ввод иногда лагает.
Даже если сцена отрисуется очень быстро — управление мышкой сильно отставало, для шутера от первого лица такое отставание критично. Из-за этого игра тоже казалось очень заторможенной.
В игровом коде есть два способа исполнения «игрового цикла»: requestAnimationFrame() и setInterval() . Одна из версий частично решает проблему скорости ввода на одних системах, другая — на других. От этого ситуация запутывается еще сильнее.
Таких мелких проблем было много, но у всех была одна причина — в JavaScript-версии все очень сильно зависит от реализации браузера, который часто делает не то, что вы от него хотите. В C++ такой проблемы не было в принципе.
Скорость разработки
И JavaScript, и C++ я знаю достаточно хорошо, поэтому скорость была примерно одинаковой. В C++ иногда возникает нужда реализовать вещи, о которых в JavaScript думать не надо, но зато система типов C++ помогает в отлове багов и опечаток. «Хвала» современным браузерам — JavaScript отлаживать так же удобно, как C++ двадцать лет назад.
Лично я думаю, у обоих языков есть и плюсы, и минусы. В конце концов, оба они — просто инструменты для достижения цели.
Если вы решите вдруг написать свой трехмерный шутер от первого лица, я настоятельно рекомендую делать это не на JavaScript/HTML/WebGL. Для встроенных в сайты мелких игрушек или прототипов они хороши, но сделать на них полноценный, да еще и нативный продукт нереально. Ну, по крайней мере, сейчас. Кто знает, вдруг через несколько лет все станет резко наоборот. Знаю много людей, которые с таким инструментарием делают двухмерные игры, и получается прекрасно. Но для трехмерной игры от первого лица это так не работает.
Я решил продолжить работу над C++-версией. Надеюсь, что закончу в ближайшие месяцы. Вот тут можно понаблюдать за прогрессом: сайт игры.