Table of Contents
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.
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
Numbers
!!! 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.
NaN
let myValue = 7 * “same string”
In this case, instead of throwing an error, myValue will be NaN type.
Infinity
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
BigInt
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
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
length
Returns the length of a string.
prototype
Allows you to add new properties and methods to a String object.
String Methods
charAt()
Returns the character at the specified index.
concat()
Joins two or more strings, and returns a new string.
includes()
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'; break; case 'bcdfg'.includes(s[0]): letter = 'B'; break; case 'hjklm'.includes(s[0]): letter = 'C'; break; default: letter = 'D'; } return letter; }
indexOf()
Returns the index of the first occurrence of the specified value in a string.
match()
Matches a string against a regular expression, and returns an array of all matches.
search()
Searches a string against a regular expression, and returns the index of the first match.
slice()
Extracts a portion of a string and returns it as a new string.
split()
Splits a string into an array of substrings.
toLowerCase()
Converts a string to lowercase letters.
toUpperCase()
Converts a string to uppercase letters.
trim()
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);
Careful!!
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
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
Undefined
In JavaScript, a declared variable without a value, has the value undefined.
The data type for a variable that has not been assigned a value.
The type is also undefined.
let number; // values is undefined, type is undefined
Any variable can be emptied, by setting the value to undefined.
let unassigned; console.log(unassigned); //Undefined
Empty Values
An empty value has nothing to do with undefined. For example,
var name = “”; // The value is “”, the typeof is “string”
Null
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” or has an unknown value.
Null is case sensitive. You should use lowercase for 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
Is better to assign null to a variable when you want to say it is empty and unknown at first!
Simbols
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.
Symbol can be used when it is very important that variables are not equal, even though their value and type are the same.
let str1 = "Welcome to webpedia"; let str2 = "Welcome to webpedia"; console.log("These two strings are the same:", str1 === str2); //These two strings are the same: true let sym1 = Symbol("Welcome to webpedia"); let sym2 = Symbol("Welcome to webpedia"); console.log("These two Symbols are the same:", sym1 === sym2); //These two strings are the same: false
Just like a string or number, you can use a symbol as a property key. For this reason Symbol data types can be very handy as properties of objects.
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!
Converting data types
The variables in JavaScript can change types and sometimes JavaScript will does this automatically.
let num1 = 2; let num2 = "3"; console.log(num1 * num2); //6
But you have to be careful because the plus sign can be used to concatenate strings.
Therefore, instead of converting a string to a number, in the example below it will convert the number to a string.
let num1 = 2; let num2 = "3"; console.log(num1 + num2); //23
It is recommended to use conversion methods: String(), Number(), and Boolean().
String()
String() converts a variable to type String. It will takes any value, including undefined and null, and puts quotes around it.
Number()
Number() converts a variable to a number.
If that cannot be done, it will change the value into NaN (not a number).
let strToNr = "webpedia"; strToNr = Number(strToNr); console.log(strToNr, typeof strToNr); // NaN number
Boolean()
Boolean() converts a variable to a Boolean.
This will be true for everything except for null, undefined, 0 (number), an “” empty string, and NaN.
let strToBool = "false"; strToBool = Boolean(strToBool); console.log(strToBool, typeof strToBool); //true boolean let strToBool = ""; strToBool = Boolean(strToBool); console.log(strToBool, typeof strToBool); // false boolean
Objects
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.
Arrays
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!
JavaScript provides nice built-in array functions that we can use to work with arrays. See here How to use built-in JavaScript Array Functions. 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) The reverse() method reverses the order of the elements in an array. The reverse() will change the original array. sort() method sorts an array alphabetically Because JavaScript sorts alphabetically. This means that “10” is lower than “4” because “1” is lower than “4” Here is the syntax of the sort method in javascript: 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 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(function(a,b){return a-b}); sort(function(a,b){return b-a}); 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 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. Before ES2015, JavaScript had only two types of scope: Global Scope and Function Scope. Variables declared outside any function have Global Scope. Global variables can be accessed from anywhere in a JavaScript program. Variables declared inside a function have Function Scope. They can only be accessed from inside the function where they are declared. Variables declared with the var keyword cannot have Block Scope. Variables declared inside a block {} can be accessed from outside the block. 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: ES2015 introduced two new JavaScript keywords: let and const, which provides Block Scope for variables and constants. 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. 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. 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 The x declared in the {} block, in this example, is not the same as the x declared outside the block.
JavaScript Array Methods
toString()
pop()
push()
Array reverse() Method
console.log(['h', 'e', 'l', 'l', 'o'].reverse());
[ 'o', 'l', 'l', 'e', 'h' ]
sort()
var num = [1,3,10,4,5];
console.log(num.sort()); //[ 1, 10, 3, 4, 5 ]
Why?
How to sort numeric array in javascript?
array.sort([compareFunction]);When compare eFunction is not provided:
When compare Function is provided:
Sort a numeric array in ascending order
Sort a numeric array in descending order
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
JavaScript Declarations are Hoisted
Javascript variables Scope
Global Scope
Function Scope
Block Scope
{
var x = 5;
}
// x can be used here
Redeclaring Variables
var x = 5;
// Here x is 5
{
var x = 1;
// Here x is 1
}
// Here x is 1
About Let and Const
{
let x = 5;
}
// x can NOT be used here
JavaScript Const
{
const x = 5;
x = 1;
console.log(x); //This will give an error
}
Redeclaring a variable using the let keyword
var x = 5;
// Here x is 5
{
let x = 1;
// Here x is 1
}
// Here x is 1
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!