2. JavaScript Data Types, Scope, and Hoisting ▷ Primitive vs Objects

5/5 - (1 vote)

JavaScript variables can hold many data types: Number, BigInt, String, Boolean, Undefined, Symbols, Arrays, objects, etc

var number = 16; // Number
var color = “red”; // String
var isRed = true; // Boolean
var car = {color:”red”, type:”SUV”}; // Object

JavaScript Primitive Types

In JavaScript are 7 primitive data types. Number, BigInt, String, Boolean, Undefined, Null, Symbol are primitive types.

fastcommet SSD host

Primitive data types characteristics

  • Primitives are compared by value, they don’t have individual identities
  • A primitive is not an object and has no methods of its own.
  • All primitives are immutable, meaning they cannot be altered


!!! In JavaScript, there are no separate types for integers and floating-point numbers, although there is a separate data type for very big numbers.

JavaScript numbers can be with, or without decimals:
var x = 4;
var y = 4.42;

All number values are stored as 64-bit floating point.

Also, we can define hexadecimal numbers by putting zero x at the beginning of a number (eg 0x1C) or binary numbers by putting zero b before the number (eg 0b11110001).

Extra-large or extra small numbers can be written with the exponential notation:
var y = 442e5; // 44200000
var z = 442e-5; // 0.00442

The JavaScript’s highest integer value that a number can go to without losing precision is +/- 9007199254740991

Are also 2 special types of numberb in JaVaScript: NaN and Infinity.


let myValue = 7 * “same string”
In this case, instead of throwing an error, myValue will be NaN type.


Division by 0 gives you another special value Infinity.
let myValue = 7 / 0

or when we use too high a value as for example:
let myValue = Math.pow(7,9999) //Infinity


In JavaScript, the number type cannot represent integer values larger than 253 (or less than -253 for negatives).
That’s about 16 decimal digits. If you need a higher value you must use BigInt.

A BigInt is created by appending n to the end of an integer literal or by calling the function BigInt().
const theBiggestInt = 9007199254740991n

Big numbers, are only accurate to about 15 digits. For this reason, is not a good idea to compare two decimal numbers for equality in JavaScript, since two numbers that should in fact be equal might not be seen as such by JavaScript.

One method of comparing 2 decimal numbers is to multiply them by some power of 10 and then use math.round to get rid of the rest of the digits.

We’re not allowed to directly add regular numbers to BigInts.

So for example, 9n plus 1, would give us an error.

If You wanna add a regular number to a BigInt, we first have to convert that number into a BigInt.
9n + BigInt(1) = 10n


Strings are written with single or double-quotes. Also, You can define strings using backticks.

let myVar = 'Hello world';
let myVar = "Hello world";
let myVar = `Hello world`;
let myVar = `Hello ${name}`;

Backticks allow inserting the values of variables into our strings.

The escape character \

Where to use the escape character?

1. Use the escape character when You want to put double quotes inside of double-quoted strings.

let myVar = "He asking You \"How are You?\" but you did not answer.";

You can also switch the quotation marks to the opposite type of quotation marks that you want to use inside the string.

let myVar = 'He asking You "How are You?" but you did not answer.';

2. So in addition to allowing the use of quotation marks inside strings, escape characters allow us to include special characters, such as new lines \n and tabs \t inside strings.

3. If You need to put the backslash character inside a string, for example, if you need a file path, you can do that by putting two backslashes in a row inside the string.

JavaScript String Properties


Returns the length of a string.


Allows you to add new properties and methods to a String object.

String Methods


Returns the character at the specified index.


Joins two or more strings, and returns a new string.


Checks whether a string contains a specified substring. This method returns true if the string contains the characters, and false if not.

Javascript Hackerrank Switch example

Javascript Conditional Statements Hackerrank Switch example

function getLetter(s) {
    let letter;
    // Write your code here
    switch (true) {
        case 'aeiou'.includes(s[0]):
            letter = 'A';
        case 'bcdfg'.includes(s[0]):
            letter = 'B';
        case 'hjklm'.includes(s[0]):
            letter = 'C';
            letter = 'D';
    return letter;


Returns the index of the first occurrence of the specified value in a string.


Matches a string against a regular expression, and returns an array of all matches.


Searches a string against a regular expression, and returns the index of the first match.


Extracts a portion of a string and returns it as a new string.


Splits a string into an array of substrings.


Converts a string to lowercase letters.


Converts a string to uppercase letters.


Removes whitespace from both ends of a string.

How to concatenate strings in JavaScript

You can concatenate strings using the plus sign or the built-in concat() method. Both methods have the same result.

let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;

let fullName = firstName.concat(" ").concat(lastName);


JavaScript runs the statement from the left to right.

Therefore the result of the code below will be

let a = 1;
let b = 2;
let c = "a plus b is " + a + b; //a plus b is 12

To prevent this we can we could wrap the x plus y part in parentheses, so that it gets executed first:

let a = 1;
let b = 2;
let c = "a plus b is " + (a + b); //a plus b is 3


Booleans can only have two values: true or false.

They can be assigned directly:

let a = true;
let b = false;

Or they can be obtained as the result of comparison operations like:

let result = 1 < 2 //false

All the other values in JavaScript, numbers, strings, objects, and the rest can be converted to Boolean values.

For example, an empty string in JavaScript is considered false.

JavaScript falsely values

1. “”
2. 0
3. NaN
4. On
5. Null
6. undefined
7. false


In JavaScript, a declared variable without a value, has the value undefined.

The type is also undefined.
var number; // values is undefined, type is undefined

Any variable can be emptied, by setting the value to undefined.
var number = undefined;

Empty Values

An empty value has nothing to do with undefined. For example,
var name = “”; // The value is “”, the typeof is “string”


In JavaScript null is “nothing”. It is supposed to be something that doesn’t exist.

In JavaScript, null is not a “reference to a non-existing object” or a “null pointer” like in some other languages.

It is just a special value that represents “nothing”, “unknown value” or “empty”.

You can empty an object by setting it to null

Difference Between Undefined and Null

undefined and null are equal in value but different in type:

typeof undefined // undefined
typeof null // object

null === undefined // false
null == undefined // true


Symbols are values that programs can create and use as property keys without risking name collisions.

var mySymbol = Symbol();

Calling Symbol() creates a new symbol, a value that’s not equal to any other value.

Just like a string or number, you can use a symbol as a property key.
Because a symbol it’s not equal to any string, this symbol-keyed property is guaranteed not to collide with any other property.

obj[mySymbol] = “abcd!”; // guaranteed not to collide
console.log(obj[mySymbol]); // abcd!


Everything else that is not a Primitive type is an Object type.

JavaScript objects are written with curly braces {}.
var car = {color:”red”, type:”SUV”};

Read more here about JavaScrip objects.


JavaScript arrays are written with square brackets and items are separated by commas.
var names = [“Mike”, “Will”, “John”];
Array indexes are zero-based

The typeof Operator

The typeof operator returns the type of a variable or an expression:

typeof “” // Returns “string”
typeof “color” // Returns “string”

Be careful!

  • The typeof operator returns “object” for objects, arrays, and null.
  • The typeof operator return “function” for functions.

JavaScript Array Methods


toString() converts an array to a string


pop() method removes the last element from an array


push() method adds a new element to an array (at the end)

Array reverse() Method

The reverse() method reverses the order of the elements in an array.

The reverse() will change the original array.

console.log(['h', 'e', 'l', 'l', 'o'].reverse());
[ 'o', 'l', 'l', 'e', 'h' ]


sort() method sorts an array alphabetically

Be careful when trying to sort numerically arrays
var num = [1,3,10,4,5];
console.log(num.sort()); //[ 1, 10, 3, 4, 5 ]


Because JavaScript sorts alphabetically. This means that “10” is lower than “4” because “1” is lower than “4”

How to sort numeric array in javascript?

Here is the syntax of the sort method in javascript:

When compare eFunction is not provided:

When compare Function is not provided, the default mode of sorting is followed wherein the elements of the array are converted into strings and then compared according to the UTF 16 code unit values, and the elements are sorted in ascending order by default.

When compare Function is provided:

When compareFunction is provided, then the function takes over the sorting process and all the non-undefined elements get sorted based on the return value of compareFunction according to the following logic.

Sort a numeric array in ascending order

sort(function(a,b){return a-b});

Sort a numeric array in descending order

sort(function(a,b){return b-a});

Hackerrank Example – Return the value of the second largest number in a numeric array

nums = [...new Set(nums)];                // Delele Duplicates
nums.sort(function(a,b){return b-a});    // Sort Array in reverse order
return nums[1]                           // Select 2 item

Set objects are collections of unique values. Set can store any types of values whether primitive or objects. Read more here about Sets in JavaScript

JavaScript Declarations are Hoisted

In JavaScript, a variable can be declared after it has been used, meaning the variable can be used before it has been declared.

Hoisting is the JavaScript default behavior of moving all declarations to the top of the current scope (the current script or the current function).

Be careful!

JavaScript Initializations are Not Hoisted!

JavaScript only hoists declarations, not initializations.

Javascript variables Scope

Before ES2015, JavaScript had only two types of scope: Global Scope and Function Scope.

Global Scope

Variables declared outside any function have Global Scope.

Global variables can be accessed from anywhere in a JavaScript program.

Function Scope

Variables declared inside a function have Function Scope.

They can only be accessed from inside the function where they are declared.

Block Scope

Variables declared with the var keyword cannot have Block Scope.

Variables declared inside a block {} can be accessed from outside the block.

  var x = 5;
// x can be used here 

Redeclaring Variables

Redeclaring a variable using the var keyword can be problematic, because redeclaring the variable inside a block will also redeclare the variable outside the block:

var x = 5;
// Here x is 5
  var x = 1;
  // Here x is 1
// Here x is 1 

ES2015 introduced two new JavaScript keywords: let and const, which provides Block Scope for variables and constants.

About Let and Const

Variables declared with the let keyword can have Block Scope.

This means that the variables declared inside a block { with let keyword} cannot be accessed from outside the block.

  let x = 5;
// x can NOT be used here

JavaScript Const

Variables defined with const behave like let variables, except they cannot be reassigned:

Declaring a variable with const is similar to let when it comes to Block Scope.

const x = 5;
x = 1;
console.log(x); //This will give an error

Redeclaring a variable using the let keyword

Redeclaring a variable inside a block will not redeclare the variable outside the block

Unlike redeclaring a variable using var keywords, this time there will be no confusion

var x = 5;
// Here x is 5
  let x = 1;
  // Here x is 1
// Here x is 1 

The x declared in the {} block, in this example, is not the same as the x declared outside the block.

fastcommet SSD host

Hello there!

I hope you find this post useful!

I'm Mihai, a programmer and online marketing specialist, very passionate about everything that means online marketing, focused on eCommerce.

If you have a collaboration proposal or need helps with your projects feel free to contact me. I will always be glad to help you!

subscribe youtube

Leave a Comment