Sage-Code Laboratory
index<--

JavaScript Variables

A variable is a name or identifier that represents data stored in computer memory. JavaScript data can have simple basic types: {Numeric, Character, String, Date, Time} or more complex types: {objects, images, collections}. Using variables you can create computations and then display the results.

Page Bookmarks



Declaring a variable

Momentarily there are 4 ways to declare a variable in JavaScript. In next example we declare 4 variables in 4 different ways. Only first variable will have initial value, the other variables will have value: 'undefined':

Example:

// using "=" operator
first = 0
// using var keyword
var second
// using let keyword
let third
// using const keyword
const forth

Alert: For new JavaScript code, the variables should be declared using keyword: "let" and "const". Apparently "var" have some issues, leading to maintainability defects. So the plan is to deprecate "var" in future versions of JavaScript.

Assign value

A JavaScript variable can have a data type: 'numeric', 'string', 'boolean' or 'object'. To make the variable "salary" be of a numeric data type, we will simply assign a number using "=" operator. If the variable is not defined yet, it will be automatically created with initial value.

Examples:

Next example show you a variations of assignment statements that create varianles using type inference without the keyword var, let or const.

//Declare an integer variable using type inference
salary = 1000;
//Alternatively, we can assign the variable a string value:
salary = "entry level";
//We can also assign it a Boolean value:
salary = true;
//We can also declare and assign a variable
//on the same line in order to make our code shorter:
salary = 1000;
//Later in our code, we might decide we want to change
//the value of our variable. To do that,
//we simply assign our variable a new value:
salary = 2000;

Note: By changing the value of a variable we can also change its data type. We can re-declare a variable in JavaScript using "var" but not using "let" or "const". For new JavaScript code we recommend to quit using "var" that is deprecated.

Example:

In next example variable "test" is declared several times using keyword "var".

var test = "test"
console.log(test) // 'test'
var test;
console.log(test) // 'test'
var test = 0;
console.log(test) // 0

Hoisting Technique

It is not possible to declare a variable several times using "let". It is more logical not to be able to re-declare a variable. Unfortunately you can still use assignment before declaration. Next example demonstrate a property of JavaScript called "hoisting". You can use something before it is defined.

Negative test

Next example should fail because we redeclare a variable that exist using let.

a = 30;
console.log(a); //expect: 30
let a;
console.log(a); //expect: 30

Note: JavaScript is difficult to defend sometimes. Don't be discouraged it is still a good language. It just need some fixes that will be done eventually in the future. Nobody is perfect. All you need to do is… avoid traps. Do not change the meaning nor the type of variables in your code. It is a bad practice.

Multiple variables

We can declare more than one variable into a single statement. For each variable we can assign a different value. Multiple declarations are separated by comma and terminated by ";".

//declare 3 variables on single line
let driver = "John", car = "Acura", year = "1999";
//declare 3 variables in one single statement
let
 driver = "Xena",
 car = "Porsche",
 year = "2015";

Alert: A common mistake is to declare multiple variables and assume they will have same value if you only assign the last one in the list. This may lead to unexpected results. Avoid this trap!
let test1, test2 = "test";
console.log(test1) // undefined
console.log(test2) // 'test'

The correct way to declare multiple variables having same initial value must use "transitivity" property of assign operator:

let a = b = c = 10; //same initial value
console.log(a,b,c) //expect: 10, 10, 10

Function Typeof()

JavaScript is a dynamic language. That means the type of variable can be changed using assignment. Current type can be investigate using function typeof(). This can be useful if you wish to do some 'introspection before using operators on the wrong type.

Numeric Type

JavaScript do not make a differentiation between integers and float numbers like other languages. There is only one numeric type in JavaScript: "number". In next example I try to change the type, but JavaScript is reporting the same type.

a = 30; // integer
type = typeof(a);
console.log(type); //'number'
a = 1.5; // float
type = typeof(a);
console.log(type); //'number'

Numeric Operators

JavaScript provides operators for standard arithmetic operations: addition, subtraction, multiplication, and division, 'along with modular division and negation. Usage of these operators is straightforward; here are some examples:

Operator Description Example Result
+ Addition 5 + 2 7
- Subtraction 5 - 2 3
* Multiplication 5 * 2 10
/ Division 6 / 2 3
% Modulus 5 % 2 1
++ Increment let x = 5;
x++;
6
-- Decrement let x = 5;
x--;
4
** Power 2 ** 3; 8

Example:

/* pre increment/decrement */
a = 3; //establish test fixture
document.write('++a =', ++a,'<br>' );
document.write('--a =', --a,'<br>' );
/* post increment/decrement */
a = 3; // reset test fixture
document.write('a++ =', a++,'<br>' );
document.write('a-- =', a--,'<br>' );
a = 3; // reset test fixture
document.write('a +1 =', a + 1,'<br>');
document.write('a +1 =', a - 1,'<br>');
a = 3; // reset test fixture
document.write('a / 2 =', a / 2,'<br>');
document.write('a * 2 =', a * 2,'<br>');
document.write('a ** 2 =', a ** 2,'<br>');
document.write('a % 2 =', a % 2,'<br>');

Notes:

Bitwise operators

Bitwise operators are operating on every bit in a binary representation of a number. These are numeric. In example we use ½ byte as an example but in reality such small number is not possible. Any number is at least 8 bit long.

Symbols

Here is a HTML table enumerating all the bitwise operators in JavaScript with descriptions:

Operator Short Name Description
& AND Sets each bit to 1 if both bits are 1.
| OR Sets each bit to 1 if one of two bits is 1.
^ XOR Sets each bit to 1 if only one of two bits is 1.
~ NOT Inverts all the bits.
<< LS Shifts left by pushing zeros in from the right and let the leftmost bits fall off.
>> RS Shifts right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off.

Examples:

Here is an HTML table explaining the bitwise operators in JavaScript with 4 byte examples

ValueA & B A | B A ^ B A >> B A << B
A10101010101011011101
B01100110011021
==00101110110000111010

Use-Cases

Bitwise operators are common in low level programming and less used in JavaScript. However you can use these operators for some high end use-cases.

Boolean Type

Boolean type is a logical data type that can have values: true or false. If you use Boolean variables in numeric expressions they are automatically converted: true = 1 and false = 0.'Boolean types are also known as Logic types.

Example:

a = true;
console.log(typeof(a)); //Boolean
console.log(a); //true
a = a + 1;
console.log(a); //2
console.log(typeof(a)); //Numeric

Boolean operators:

Boolean operators in JavaScript are similar to C operators and are based on one or two characters.

//logical "and": &&
console.log(true && true); // true
console.log(true && false); // false
console.log(false && false);// false
//logical "or": ||
console.log(true || true); // true
console.log(true || false); // true
console.log(false || false);// false
//logical "not": !
console.log(!true); // false
console.log(!false); // true

Falsey values

The following values evaluate to false, also known as falsy values

Relation Operators

A relation operator can be used to compare two values. Usually values are numeric but can be also strings or objects.'Relation operators are also known as comparison operators.'These operators produce a Boolean result. In the next table,'we use variable x = 5 to demonstrate various examples.

/* anonymous block */
{
  let x = 5      // create a test fixture
  console.log(x) // check variable x

  /* test relation operator "==" */
  console.log("is x equal to 5? ", x == 5)
}

Symbol Description Expression Result
== equal to x == 8 false
x == 5 true
x == "5" true
=== equal value and equal type x === 5 true
x === "5" false
!= not equal x != 8 true
!== not equal value or not equal type x !== 5 false
x !== "5" true
x !== 8 true
> greater than x > 8 false
< less than x < 8 true
>= greater than or equal to x >= 8 false
<= less than or equal to x <= 8 true

JavaScript strings

A string is a sequence of characters. That is not quite true for Unicode. An Unicode string is a sequence of code points.'JavaScript support Unicode symbols in string literals.'Strings are immutable. They cannot change, we can only ever make new strings.

String literals

String literals are surrounded by single quotes: '…' or double quotes "…". You can use quotes inside a string, as long as they don't match the quotes surrounding the string, 'otherwise you must use escape symbol "\" in front of quotes matching the surrounding quotes.

Example:

// Single quote inside double quotes
answer = "It's alright";
// Single quotes inside double quotes
answer = "He is called 'Johnny'";
// Double quotes inside single quotes
answer = 'He is called "Johnny"';
// Escape for single quote
answer = 'It\'s sister is famous!';

Join two strings

The process of joining two strings is also called concatenation. We create a new string using concatenate operator "+". Below is an example of concatenating two string variables.

//create two string variables
numberOfProducts = "five"
productType = "potato"
//create a third variable and assign to it a value
//by concatenating the two string variables we created earlier
inventory = numberOfProducts + productType

Template literals

Templates are special string literals enclosed in back-quotes like: `demo`. There is a useful method for string manipulation called: "string interpolation". For this string template can use placeholders like: ${var}. A placeholder will be replace automatically by values.

Example:

//define object
let car = {type:"Fiat", model:"500", color:"white"}
//read object properties
console.log(`car type = ${car['type']}`)
console.log(`car model = ${car.model}`)
console.log(`car color = ${car.color}`)

Notes:

Example:

let a = 5;
let b = 10;
console.log(`${a} + ${b} = ${a + b}`);
console.log(`2 * (${a} + ${b}) = ${2 * a + b}`);

Output:

5 + 10 = 15
2 * (5 + 10) = 20

Splitting a string:

A string is an object so it has methods. String methods can be call using the dot notation. For example if str="Hello World" is a sting then you can use method: 'split() like this: str.split(" ") and this will create an array of 2 words: ["Hello","World"]. The string was split in two parts and space (the separator) is discarded.

// define a string
let str = "hello world"
// use method split()
let arr = str.split(" ")
// display the result
console.log(arr); // ["hello", "world"]

Extract a character:

There are 2 safe methods for extracting string characters:

Example:

// define a string
let str = "Hello World"
// safe access
w = str.charAt(6);
console.log(w); // W
// unsafe access
h = str[0]
console.log(h); // H
// safe access to code
c = str.charCodeAt(0);
console.log(c); //72

Note: Do not use a string like an array with index: str[0]. This is not safe, except if your string is using ASCII characters or printable Unicode symbols and no modifiers. If this is not true accessing a string character by index is a bad practice.

String methods

The string object has numerous predefined methods that are not in my scope to present. If you need a method you should consult the MDN reference documentation. To search this documentation type in google search box: MDN <function_name> for example: '"mdn charAt()", most of the time first hit will lead you to details about correct function.

Method Description
charAt() Returns the character at the specified index (position)
charCodeAt() Returns the Unicode of the character at the specified index
concat() Joins two or more strings, and returns a new joined strings
endsWith() Checks whether a string ends with specified string/characters
fromCharCode() Converts Unicode values to characters
includes() Checks whether a string contains the specified string/characters
indexOf() Returns the position of the first found occurrence of a specified value in a string
lastIndexOf() Returns the position of the last found occurrence of a specified value in a string
localeCompare() Compares two strings in the current locale
match() Searches a string for a match against a regular expression, and returns the matches
repeat() Returns a new string with a specified number of copies of an existing string
replace() Searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced
search() Searches a string for a specified value, or regular expression, and returns the position of the match
slice() Extracts a part of a string and returns a new string
split() Splits a string into an array of substrings
startsWith() Checks whether a string begins with specified characters
substr() Extracts the characters from a string, beginning at a specified start position, and through the specified number of character
substring() Extracts the characters from a string, between two specified indices
toLocaleLowerCase() Converts a string to lowercase letters, according to the host's locale
toLocaleUpperCase() Converts a string to uppercase letters, according to the host's locale
toLowerCase() Converts a string to lowercase letters
toString() Returns the value of a String object
toUpperCase() Converts a string to uppercase letters
trim() Removes white-space from both ends of a string

Mozilla manual MDN: String Methods

Type Coercion

Thouhj JavaScript do not declare type, a variable has type nevertheless. Sometimes you need to convert the value from one type to other type. This can be done using type coercion that is automatic (implicit) or explicit.

Implicit Coercion

In the next example we concatenate strings with numbers. This is possible in JavaScript. However you must know JavaScript can surprise you from time to time with weird results. Do not let JavaScript rule you. I suggest to use explicit coercion.

/* default concatenation */
a = 3, b = "4"; // fixture
console.log(typeof(b)); // string
console.log(typeof(a)); // number
document.write('a, b = ', a, ',', b, '<br>');
document.write('a + b =', a + b,'<br>' ); // 34
document.write('b + a =', b + a,'<br>' ); // 34
/* automatic conversion */
document.write( 'b = ', b, '<br>')
document.write('b - a =', b - a,'<br>' ); // 1
document.write("b / 2 =", b / 2,'<br>'); // 2
document.write("b * 2 =", b * 2,'<br>'); // 8
document.write("++ b =", ++ b ,'<br>'); // 5
document.write("++ b =", -- b ,'<br>'); // 4

Explicit Coercion

Do not relay on automatic implicit conversions. This may produce unexpected results or logical errors. It is possible to use explicit conversion instead. In the next example we use coercion function Number() to convert a string into a number

/* given fixture */
a = 3, b = "4";

/* explicit coercion */
c = a + Number(b); // 7

Special Values

There are some special values in JavaScript that you must learn to understand possible strange situations when an unexpected result pop-up or an exception that you can not explain.


Read next: Functions