JavaScript (Part 003: Variables, Constants, Operators, Data Types, and Code Comments)

JavaScript (Part 003: Variables, Constants, Operators, Data Types, and Code Comments)

What is a variable?

It's simply a data container or data storage. It's a core feature, not just of JavaScript but of most programming languages. In most programs we're going to work with some data and for that we use variables.

In JavaScript, we create a variable by using the 'let' keyword, then a name of our choice (with some naming rules of course!). This action is called variable declaration.

Here, we created (declared) a variable which is named, 'myVariable':

No alt text provided for this image

We can also assign (initialize) a value to the variable when we declare it. After the variable name we can add an equal sign and then the value we want to store in the variable. So we can do declaration and initialization at the same time:

No alt text provided for this image

We also can separate variable declaration and variable assignment:

No alt text provided for this image

As you might have noticed, when we only need the 'let' keyword, if we introduce a variable for the first time. If we then assign a new value to it , we don't repeat that keyword. After assigning a value to a variable, we can change it later in code.

No alt text provided for this image

Or:

No alt text provided for this image
A variable is a data container where the value can change, does't have to but often it will.

What is a constant?

We have a special form of variable: Constants . That's still a data container but instead of with the 'let' keyword, we create it with the 'const' keyword. The special thing about constants created with the 'const' keyword is that there, we can't change the value. If we try to do that, we'll get an error. So, there the values must not change.

No alt text provided for this image

If we write the following code, we will get an error:

No alt text provided for this image

Why constants?

Sometimes in our code, we have values which never change which we still want to store in such a data container, so that we can initialize them in a central place (e.g. at the beginning of our file) and then use them throughout our program, maybe use the same constant multiple times in different places, so we will always reference the same single constant and if we then ever, in code when writing our code, we change that value, we change it in one place instead of many places. We typically want to use constants as often as possible. It makes our intentions very clear. If we have a value which actually never changes throughout the life cycle of our program (or of the part of our code where we use it), then we want to make that clear so that if any other developer ever reads our code quickly understands that this piece of data is never going to change. It simply makes our code easier to understand for others.

Rules and recommendations for naming variables and constants

1.Use 'camelCase' naming convention:

Our name starts with a lower case character and is only one word so there are no blanks no no white space there, that would be actually forbidden but every word inside of the word, starts with an upper case character to make it more readable. (Examples: userName, phoneNumber, authorOfBook, ...)

2.Use descriptive names:

The variable name should describe which kind of data we are storing in there.

3.Be Aware Of JavaScript's case-sensitivity:

JavaScript is case-sensitive and this means that it really matters whether a character is a capital character or not. (phoneNumber is different from PhoneNumber.)

4.Don't use keywords:

Using keywords (like 'let', 'const', 'function', ...) is not allowed as variable names, because JavaScript will not be able to distinguish between the variable name and the keyword.

5. Keep the following rules and recommendations is mind:

  • Our variable names can be made up of any letters or digits. (For example: group3, tickets2Sell, ...)
  • We can also use the dollar sign special character ($) any where in our variable name (even at the beginning of that). (For example: $bookTitle, special$Number, ...)
  • We can use the underscore character (_) at the beginning of our variable or any where inside of it. (For example: _userId, greeting_Message, ...)
  • 'snake-case' is allowed but it is a bad practice (for example: user-name)! We can have it in some other programming languages like python but not in JavaScript.
  • We must not start our variable name or constant with a digit. (For example: 32Players)
  • When it comes to special characters, there are special rules. We must not use special characters (except dollar sign and underscore), neither at the beginning of our variable nor anywhere else. (So dashes or white spaces are not allowed!).

Semicolon in JavaScript

In JavaScript, using the semicolon is generally optional. There are some rare niche cases where it's not optional but we can avoid these cases and hence we can write JavaScript code without semicolons. The following code is valid in JavaScript:

let bookTitle
bookTitle = 'Once upon a time'        

We can't omit the semicolon when having two expressions in one line. The following code is not valid in JavaScript:

let const a=1 let const b=2        

We should convert it to this:

let const a=1; let const b=2        

Ultimately it is up to you as a developer to add semicolons or not. But you should stick your choice.

What are operators?

Consider the following JavaScript code:

No alt text provided for this image

We are referring to the 'calculationResult' on the left side of the equal sign and on the right sign of the equal sign, we are reading and using it's current value. First, we are doing some calculation on the right side of the equal sign and then assign it to the variable (in this example we using the same variable in both sides). So, the variable gets overwritten the final value of the variable will be 10.

Operators are syntax features in JavaScript that allow us to manipulate values. There are the typical mathematical operators we are used to (+, -, *, /) ('+' for addition, '-' for subtraction, '*' for multiplication and '/' for division). There also is the modulus operator (%), which divides two numbers and returns the remainder. There also is the exponentiation operator which allows us to use exponentiation in a number (**). There are also other operators in JavaScript, like the assignment operator (=) which we use to assign a value to a variable.

We are not limited to two operators per line or to one. The code below is valid in JavaScript and by default and JavaScript follows normal mathematical rules. (We can change that order by using parentheses.) (Here the final value will be 38)

No alt text provided for this image

Shortcut operators:

There are a couple of shortcut operators:

Consider the following line of code (Suppose we previously declared result and newValue):

result = result + newValue;        

For code like this, there is a shortcut. We can absolutely write it like this but if we assign the result to the same variable we are using on the right side of the equal sign, we can omit that variable there on the right side, omit the operator and instead write plus equal (+=)

result += newValue;        

That's exactly the same as the previous line of code.

The same is available for other operators.

There are also other shortcuts (other shorthand operators), if we have the case that we want to set a new value to a variable and that is the current value plus one (exactly plus one!)

Suppose we previously declared result. The following two lines of code are equivalent:

result = result + 1;

result++;        

This is also available for minus. Suppose we previously declared result. The following two lines of code are equivalent:

result = result - 1;

result--;        

It's not available for multiplication or division because that doesn't make any sense (that would be the same number).

++ : increment operator

-- : decrement operator

Which data types are available for us to use in JavaScript?

1.Numbers:

We can use positive, negative, non-decimal numbers and numbers with decimal places.

Examples: 11, -6, 31.84, -23.917, ...

  • Numbers with decimal places, are called floats or floating point numbers (like 4.591, -74.2116, ...).
  • Numbers without decimal places are called integers (like 2, -18).
  • We use numbers for any code where we need to calculate something or where we just need to work with a number.

2.Strings(Text):

Sometimes we need text (e.g. name of a logged in user, messages, ...). We call them strings not just in JavaScript but in other programming languages as well.

We can actually create string by wrapping our text between single quotes ('Hello'), double quotes ("Hello") or back ticks ( `Hello`). All three create a valid string. We can use whatever we want , we just should be consistent though the third option (back ticks), that's kind of special.

Strings are important for outputting results, for gathering user input, for showing messages, ...

'' or "" represent an empty string.

let firstEmptyString = '';
let secondEmptyString = "";        

If we wrap a calculation with single (or double) quotes, it will be treated as text and therefore JavaScript won't even try to execute it in a mathematical way.

let calculationResult = (22 + 32) / 6 * 2 - 15;

let calculationDetail = '(22 + 32) / 6 * 2 - 15';        

After the execution of the code above, we will have the following values stored in variables:

calculationResult : 3 (a number)

calculationDetail: (22 + 32) / 6 * 2 - 15 (a string)

We can't open a string with a double quote and try to close it with a single quote (or the other way around!). We always have to close a string with the character (single or double quote) with which we opened it. Both of the following lines of code are invalid:

let myInvalidString1 = "Tom is cooking dinner';

let myInvalidString2 = 'Tom is cooking";        

How can we output a single (or a double) quote?

When we open something with single or double quotes, everything in between the opening and closing single or double quote will be one piece of text. So, if we want to output a single quote character we can take advantage of double quotes and if we want to output a double quote we can use single quotes to wrap our string.

let myString1 = "She is called 'Nicole'.";

let myString2 = 'She is called "Nicole".';
        

After the execution of the code above, we will have the following values stored in variables:

myString1 : She is called 'Nicole'.

myString2 : She is called "Nicole".

String concatenation: We can build a string from multiple substrings. Java script actually can also work with plus if we're using it with strings, then it will not try to use plus in a mathematical way, instead it will just combine multiple strings, to a longer text piece.

let firstString = "Hello";

let secondString = "JavaScript";

let finalString = firstString + secondString;        

After the execution of the code above, the value of the finalString variable will be "HelloJavaScript". Of course we could directly also use the values for concatenation:

let finalString = "Hello" + "JavaScript";        

... and the result would be the same as before.

The plus operator (+) has two different meanings while working with numbers and strings. If we use it between two (or more) numbers, it will add those numbers but if we use it between two (or more) strings, it will concatenate those strings.

Using back ticks instead of single or double quotes : Back ticks give us access to a special syntax. If we have a variable in our string, we can use a dollar sign ($) and then an opening and closing curly braces and now we can put our variable or any expression which yields some result, which can be output as text, between our opening and closing curly braces.

No alt text provided for this image

The value of the variables will be :

totalMembers: 28

membersDescription: There are 28 in our website.

So, if want to have some text in which we want to embed or inject some dynamic value (e.g. the result of some calculation or the value that's stored in a variable or a constant) then this would be a nice approach. It is simply shorter and saves us the manual string concatenation. This syntax is also called a JavaScript template literal.

One convenient thing about template literals is that we can easily write multi line strings there. With multi line strings, we mean strings which really do have a line break in them. (For a normal string with single or double quotes, this would not be allowed!). This can help us with readability. This is not a visual thing in the IDE but that the kine breaks really are part of the string.

let myMultilineString = `Nice to
    
                        meet you!`;        

If we inspect the element, we will see that indeed the white space is considered!

The special '\' (back slash) character

When we are working with normal strings (a string enclosed by single or double quotes), to add a line break, that is possible with a special character (a special combination of characters to be more precise). We add a back slash and then 'n' (\n). What this will do if it would be rendered to the screen is it will not output '\n' there but instead it will treat this as a line break.

let anotherMultilineString = 'Nice to\nmeet you';        

The output of the above code (value stored in the anotherMultilineString variable) will be:

Nice to

meet you!

Using a back slash in a string has a special meaning, it escapes the character that comes after the back slash, which means the character after the back slash is not treated as a normal character with it's normal meaning but instead combined with the back slash, it gets a special meaning.

Examples:

\n : inserts a new line

\t: inserts a horizontal tabulator

\': inserts a single quote

\\: inserts a back slash

3.Booleans:

Booleans are effectively values which have one of two possible values , true or false. They really shine once we want to use control structures, if statements, ... in our code.

4.Objects:

Objects allow us to group data. We create an object with curly braces and then we have key-value pairs in there separated by commas. We use that for grouping or relating data. For example, suppose we want to store the information of some cars. Each car might have a name, a model, and so on. We want to use them as one piece of information. We can have an empty object or an object with key-value pairs. Often we will write object across multiple lines (that's not required, just to make it more readable!). The key names can be anything (but should be descriptive) and then separated with a colon and then we add the value. Values can be anything, can be numbers, strings, arrays, or other objects (we can also have objects in objects).

let firstCarObject = {};

let secondCarObject = {
                        name: 'Fiat',
                        model: 410,
                        color: 'white'
                      };        

  • We use "{}" to group the data. A semi-colon ";" is used after the closing curly brace.
  • key-value pairs are separated via a comma ",", not via a semi-colon. Using a semi-colon inside of an object (between { and }), would be a syntax error!
  • Values are assigned to keys (or properties) via a colon ":", not via an equal sign "=". Using an equal sign inside of an object (between { and }) would be a syntax error!

The example below would throw an error:

let worstCar = {
                 name = 'Fiat';
                 model = 410;
                 color = 'white'
               };        

Suppose we want to access one value from an object (not the full object). We use the name of the object and then we use the dot notation, we add a dot and a dot tells JavaScript that on the object in front of the dot, we want to access one of the properties (or keys), so one of the data pieces that belongs to this object: objectName.objectProperty

let sampleCar = {
                        name: 'Fiat',
                        model: 410,
                        color: 'white'
                      };        

To access the value of the 'name' property of the sampleCar object: sampleCar.name

5.Arrays:

An array is simply a list of data. They are great if we need to store a list of data, a list of transactions and we can store any data in there. It can be an array of integers (numbers without decimal places), an array of text, an array of floats (numbers with decimal places), an array of objects, even an array of arrays is possible and we can also mix data in there. We can have an array that has numbers and text elements and so on. Arrays are created with the square brackets. An array can be either empty or with some initial data and there, each element is separated from the other elements by a comma.

let numbers = [];

let myNumbers = [1, 4, 10];        

If we want to access a specific element in the array, we do this by adding square brackets after variable name and in there we add the index (the position of the element we want to extract.). Arrays are zero-based (it's the case in most programming languages), which means the first element in an array has an index of zero.So, index zero would refer to the first element, index one to the second element, index two to the third element and so on.

let carManufacturers = ['BMW', 'Toyota', 'Ford', 'Hyundai'];        

Now to access the elements:

carsManufacturers[0] : BMW

carManufacturers[1] : Toyota

carManufacturers[2] : Ford

carManufacturers[3] : Hyundai

carManufacturers[4] : undefined (It is a special data type)

carManufacturers[5] : undefined (It is a special data type)

6.Special Data Types and Values (undefined, null and NaN):

null and undefined are both values and data types. NaN is a value which looks like a data type.

  • "undefined" is the default value that uninitialized variables have. So if we create (declare) a variable and we don't assign a value at the beginning with the equal sign, then this variable is undefined. As another example, with we try to access an element in the array at an index where no element was created yet, then we tried to access an element which wasn't there and therefore we got back a value of undefined. It's a separate data type! We should never assign undefined to a variable on our own (someVariable=undefined) because that's just a default value we have if something has never been assigned to a variable.

let myVariable;

let someEuropeanCountries = ['Netherlands', 'Germany', 'Sweden', 'Norway'];

        

Now if aim to access the following variables we will get undefined:

myVariable : undefined

someEuropeanCountries [4] : undefined

  • "null" is very similar to "undefined", it means that there is no there is no data but "undefined" is the default value for variables and so on where we never assign a value. "null" is never a default value on the other hand instead we have to set something to "null" to use that variable and that's often used if we want to reset or clear a variable.

let totalProducts = 69;

totalProducts = null;        

Now 'totalProducts' has the value of 'null' (We cleared this variable!)

  • "NaN" stands for "Not a Number" and technically, unlike "undefined" and ''null" which also are their own types, this not a type, instead it's type of number, therefore we can use it in calculations where we work with numbers. The idea behind "NaN" is that it's like an error code if we run a calculation with something that doesn't include a number. So if we have a multiplication with text or anything like that, then we would get "Not a Number" as a result and if we use a "Not a Number" in a calculation, we also get "Not a Number" as a result. For example the result of the following calculations will be "NaN":

6 * 'Hello'

10 / NaN

Converting data types:

Sometimes in our code, we have to change the type of a variable or a constant. For instance, whatever we get from a user, from a HTML input in our JavaScript code will always be a string (even though we enter a number and even though the user input is of type number!!!). That's how JavaScript and the browser works.

This is the HTML code snippet for a user input of type number which in the end, gives us a string:

<input type="number" id="number-input">        

If we have a string and a number and we try to combine (add them with '+' operator), JavaScript does not convert the string to a number, and do the calculation. It does the safer thing because it doesn't know whether what we entered in the input as a string, could be treated as a number or not and therefore converts it to a string and concatenates it to a string.

let myNumber = 23;

let myString = "This is a text";

let result = myNumber + myString;        

After the above code gets executed, the value of result would be "23This is a text".

To convert a string to a number, we have a function (we will talk about functions in the next article) built into the browser or built into JavaScript, which is called "parseInt". We also have "parseFloat". The difference is that "parseInt" will try to parse some text (a string), as a number without decimal places and "parseFloat" will do the same with decimal places. (For example if we enter 10, with parseFloat, this will be parsed as 10.0, with parseInt if we enter 10.1, it would give us 10.) So parseInt and parseFloat are two built-in functions in JavaScript that will take a string as an input (as a parameter) we can pass in, and will then convert this text into a number. Of course that can fail. If we have some text like "Good morning!", "parseInt" would actually not be able to convert this to a number, instead it would convert it to "NaN".

Suppose we have a user input of type number and we want to do some calculations (for example double that value) on the number that the user entered. (We stored that value in a variable named userInputNumber)

let newValue;

newValue = 2 * parseInt(userInputNumber);        

Instead of "parseInt", we can also use a plus, even without parentheses in front of the string. This will also convert the string to number. (That's the shorter form of doing that conversion!)

let newValue

newValue = 2 * +userInputNumber;        

Of course "parseInt" and "parseFloat" are more explicit about what they are doing and they allow us to be more specific about which kind of number we want (The plus will give us the best fitting number). The plus is easy to overlook.

If we ever would want to convert a number to a string, we could do this as well by using another built-in function which converts a number to a string (that's toString function!)

Suppose we have a number stored in a variable named myNumber. To convert it to a string:

let myText;

myText = myNumber.toString();        

Now, myText has a string representation of that number.

Mixing Numbers and Strings:

Adding a string to a number would lead to string concatenation :

5 + '5' => '55'

That happens because the '+' operator also supports strings (for string concatenation). It's the only arithmetic operator that supports strings though. (For example 'Hello' - 'Hell' will not work and gives "NaN"). Only '+' supports both strings and numbers. Thankfully, JavaScript is smart and therefore is actually able to handle codes like:

5 * '5' => 55 (It yields the number 9, not a string '9'). Similarly '-' and '/' work:

5 - '5' => 0 , 5 / '5' => 1

The typeof operator:

It's a keyword that lets us evaluate the type of a variable at runtime. Follow the examples:

typeof "JavaScript is easy to learn!" : "string"

typeof 85 : "number"

typeof -29.31 : "number"

typeof true : "boolean"

typeof false: "boolean"

typeof [3, 6, 11] : "object" (!)

typeof {name:"Saeid", age: 29} : "object"

typeof undefined : "undefined"

typeof null : "object" (!)

typeof NaN : "number"

As you saw, an array is technically of type object, so there is no special array type.

Code Comments

A feature which we can use in JavaScript and many other programming languages are comments. We add comments to our code to make it more understandable to fellow developers or to ourselves if we were coming back to our code after a couple of month of break or something like that.

A comment in JavaScript can be added in two ways:

1.We can add it, like we add regular code by adding two forward slashes (//). (Look at the code in green below.) :

No alt text provided for this image

This means that this is there for people to read but has no effect on our code . It's not executed as code.

2.If we have a longer comment to write which should be split across multiple lines, we can of course add another line of comments with other forward slashes:

No alt text provided for this image

But we can also add a block comment adding a forward slash and then a star and then a star (/*) and then we have to close the comment with a star and another forward slash (*/):

No alt text provided for this image

We can also add a comment inline, so after some code:

No alt text provided for this image

We should keep in mind the followings:

  • We shouldn't comment the obvious. We don't want to overdo!
  • We don't want to write long text. People won't read them at all. Instead we want to write short to-the-point comments that add some extra context or understanding that isn't obvious from looking at code.

Source: Udemy-JavaScript-The Complete Guide 2020

To view or add a comment, sign in

More articles by Saeid Haddadi

Insights from the community

Others also viewed

Explore topics