In JavaScript, variables don’t have types, values do.
Data or values have data types. Data types describe the characteristics of data. Data types can be divided into two:
Primitive data types in JavaScript include:
Non-primitive data types in JavaScript includes:
Now, let us see what exactly primitive and non-primitive data types mean. Primitive data types are immutable(non-modifiable) data types. Once a primitive data type is created we cannot modify it.
Example:
let word = "JavaScript";
If we try to modify the string stored in variable word, JavaScript should raise an error. Any data type under a single quote, double quote, or backtick quote is a string data type.
word[0] = "Y";
This expression does not change the string stored in the variable word. So, we can say that strings are not modifiable or in other words immutable. Primitive data types are compared by its values. Let us compare different data values. See the example below:
let numOne = 3;
let numTwo = 3;
console.log(numOne == numTwo); // true
let js = "JavaScript";
let py = "Python";
console.log(js == py); //false
let lightOn = true;
let lightOff = false;
console.log(lightOn == lightOff); // false
Non-primitive data types are modifiable or mutable. We can modify the value of non-primitive data types after it gets created. Let us see by creating an array. An array is a list of data values in a square bracket. Arrays can contain the same or different data types. Array values are referenced by their index. In JavaScript array index starts at zero. I.e., the first element of an array is found at index zero, the second element at index one, and the third element at index two, etc.
let nums = [1, 2, 3];
nums[0] = 10;
console.log(nums); // [10, 2, 3]
As you can see, an array, which is a non-primitive data type is mutable. Non-primitive data types cannot be compared by value. Even if two non-primitive data types have the same properties and values, they are not strictly equal.
let nums = [1, 2, 3];
let numbers = [1, 2, 3];
console.log(nums == numbers); // false
let userOne = {
name: "Trishan",
role: "Software Developer",
country: "Nepal",
};
let userTwo = {
name: "Trishan",
role: "Software Developer",
country: "Nepal",
};
console.log(userOne == userTwo); // false
Rule of thumb, we do not compare non-primitive data types. Do not compare arrays, functions, or objects. Non-primitive values are referred to as reference types, because they are being compared by reference instead of value. Two objects are only strictly equal if they refer to the same underlying object.
let nums = [1, 2, 3];
let numbers = nums;
console.log(nums == numbers); // true
let userOne = {
name: "Nischay",
role: "Playing Valorant",
country: "Nepal",
};
let userTwo = userOne;
console.log(userOne == userTwo); // true
If you have a hard time understanding the difference between primitive data types and non-primitive data types, you are not the only one. Calm down and just go to the next section and try to come back after some time. Now let us start the data types by number type.
Numbers are integers and decimal values which can do all the arithmetic operations. Let’s see some examples of Numbers.
let age = 17;
const gravity = 9.81; // we use const for non-changing values, gravitational constant in m/s2
let mass = 55; // mass in Kilogram
const PI = 3.14; // pi a geometrical constant
// More Examples
const boilingPoint = 100; // temperature in oC, boiling point of water which is a constant
const bodyTemp = 37; // oC average human body temperature, which is a constant
console.log(age, gravity, mass, PI, boilingPoint, bodyTemp);
In JavaScript the Math Object provides a lots of methods to work with numbers.
const PI = Math.PI;
console.log(PI); // 3.141592653589793
// Rounding to the closest number
// if above .5 up if less 0.5 down rounding
console.log(Math.round(PI)); // 3 to round values to the nearest number
console.log(Math.round(9.81)); // 10
console.log(Math.floor(PI)); // 3 rounding down
console.log(Math.ceil(PI)); // 4 rounding up
console.log(Math.min(-5, 3, 20, 4, 5, 10)); // -5, returns the minimum value
console.log(Math.max(-5, 3, 20, 4, 5, 10)); // 20, returns the maximum value
const randNum = Math.random(); // creates random number between 0 to 0.999999
console.log(randNum);
// Let us create random number between 0 to 10
const num = Math.floor(Math.random() * 11); // creates random number between 0 and 10
console.log(num);
//Square root
console.log(Math.sqrt(100)); // 10
console.log(Math.sqrt(2)); // 1.4142135623730951
// Power
console.log(Math.pow(3, 2)); // 9
The JavaScript Math Object has a random() method number generator which generates number from 0 to 0.999999999…
let randomNum = Math.random(); // generates 0 to 0.999...
Now, let us see how we can use random() method to generate a random number between 0 and 10:
let randomNum = Math.random(); // generates 0 to 0.999
let numBtnZeroAndTen = randomNum * 11;
console.log(numBtnZeroAndTen); // this gives: min 0 and max 10.99
let randomNumRoundToFloor = Math.floor(numBtnZeroAndTen);
console.log(randomNumRoundToFloor); // this gives between 0 and 10
Strings are texts, which are under single , double, back-tick quote. To declare a string, we need a variable name, assignment operator, a value under a single quote, double quote, or backtick quote. Let’s see some examples of strings:
let space = " "; // an empty space string
let firstName = "Trishan";
let lastName = "Wagle";
let country = "Nepal";
let city = "Kathmandu";
let language = "JavaScript";
let job = "Software Developer";
let quote = "The saying,'Seeing is Believing' is not correct in 2020.";
let quotWithBackTick = `The saying,'Seeing is Believing' is not correct in 2020.`;
Connecting two or more strings together is called concatenation. Using the strings declared in the previous String section:
let fullName = firstName + space + lastName; // concatenation, merging two string together.
console.log(fullName);
Trishan Wagle
We can concatenate strings in different ways.
Concatenating using the addition operator is an old way. This way of concatenating is tedious and error-prone. It is good to know how to concatenate this way, but I strongly suggest to use the ES6 template strings (explained later on).
// Declaring different variables of different data types
let space = " ";
let firstName = "Trishan";
let lastName = "Wagle";
let country = "Nepal";
let city = "Kathmandu";
let language = "JavaScript";
let job = "student";
let age = 17;
let fullName = firstName + space + lastName;
let personInfoOne = fullName + ". I am " + age + ". I live in " + country; // ES5 string addition
console.log(personInfoOne);
Trishan Wagle. I am 17. I live in Nepal
A string could be a single character or paragraph or a page. If the string length is too big it does not fit in one line. We can use the backslash character (\) at the end of each line to indicate that the string will continue on the next line. Example:
const paragraph =
"My name is Trishan Wagle. I live in Nepal, Kathmandu.\
I am a student. I have learnt HTML, CSS, JavaScript, React, Redux, \
NextJS, TailwindCSS, TypeScript, and more. \
In the end of 2023, I was thinking to expand my skills and to reach \
to a peak and I started learning Web Development since 2022.\
It was one of the most rewarding and inspiring experience.\
Now, we are in 2023. I am enjoying learning, teaching, developing and \
I hope you are enjoying too.";
console.log(paragraph);
In JavaScript and other programming languages \ followed by some characters is an escape sequence. Let’s see the most common escape characters:
console.log(
"I hope everyone is enjoying the 30 Days Of JavaScript challenge.\nDo you ?"
); // line break
console.log("Days\tTopics\tExercises");
console.log("Day 1\t3\t5");
console.log("Day 2\t3\t5");
console.log("Day 3\t3\t5");
console.log("Day 4\t3\t5");
console.log("This is a backslash symbol (\\)"); // To write a backslash
console.log('In every programming language it starts with "Hello, World!"');
console.log("In every programming language it starts with 'Hello, World!'");
console.log("The saying 'Seeing is Believing' isn't correct in 2020");
Output in console:
I hope everyone is enjoying the 30 Days Of JavaScript challenge.
Do you ?
Days Topics Exercises
Day 1 3 5
Day 2 3 5
Day 3 3 5
Day 4 3 5
This is a backslash symbol (\)
In every programming language it starts with "Hello, World!"
In every programming language it starts with 'Hello, World!'
The saying 'Seeing is Believing' isn't correct in 2020
To create a template strings, we use two back-ticks. We can inject data as expressions inside a template string. To inject data, we enclose the expression with a curly bracket({}) preceded by a $ sign. See the syntax below.
//Syntax
`String literal text``String literal text ${expression}`;
Example: 1
console.log(`The sum of 2 and 3 is 5`); // statically writing the data
let a = 2;
let b = 3;
console.log(`The sum of ${a} and ${b} is ${a + b}`); // injecting the data dynamically
Example:2
let firstName = "Trishan";
let lastName = "Wagle";
let country = "Nepal";
let city = "Kathmandu";
let language = "JavaScript";
let job = "student";
let age = 17;
let fullName = firstName + " " + lastName;
let personInfoTwo = `I am ${fullName}. I am ${age}. I live in ${country}.`; //ES6 - String interpolation method (imp)
let personInfoThree = `I am ${fullName}. I live in ${city}, ${country}. I am a ${job}. I teach ${language}.`;
console.log(personInfoTwo);
console.log(personInfoThree);
I am Trishan Wagle. I am 17. I live in Nepal.
I am Trishan Wagle. I live in Kathmandu, Nepal. I am a student. I teach JavaScript.
Using a string template or string interpolation method, we can add expressions, which could be a value, or some operations (comparison, arithmetic operations, ternary operation).
let a = 2;
let b = 3;
console.log(`${a} is greater than ${b}: ${a > b}`);
2 is greater than 3: false
Everything in JavaScript is an object. A string is a primitive data type that means we can not modify it once it is created. The string object has many string methods. There are different string methods that can help us to work with strings.
Example:
let js = "JavaScript";
console.log(js.length); // 10
let firstName = "Trishan";
console.log(firstName.length); // 7
Let us access different characters in ‘JavaScript’ string.
let string = "JavaScript";
let firstLetter = string[0];
console.log(firstLetter); // J
let secondLetter = string[1]; // a
let thirdLetter = string[2];
let lastLetter = string[9];
console.log(lastLetter); // t
let lastIndex = string.length - 1;
console.log(lastIndex); // 9
console.log(string[lastIndex]); // t
let string = "JavaScript";
console.log(string.toUpperCase()); // JAVASCRIPT
let firstName = "Trishan";
console.log(firstName.toUpperCase()); // TRISHAN
let country = "Nepal";
console.log(country.toUpperCase()); // NEPAL
let string = "JavasCript";
console.log(string.toLowerCase()); // javascript
let firstName = "Trishan";
console.log(firstName.toLowerCase()); // trishan
let country = "NEPAL";
console.log(country.toLowerCase()); // nepal
let string = "JavaScript";
console.log(string.slice(0, 4)); // Java
console.log(string.slice(4, 10)); // Script
// If only one argument is given then it is regarded as starting index, and stopping index is set to the end of the string
console.log(string.slice(4)); // Script
let country = "Nepal";
console.log(country.slice(0, 3)); // Nep
console.log(country.slice(2, 5)); // pal
console.log(country.substring(1)); // epal
let string = "30 Days Of JavaScript";
console.log(string.split()); // Changes to an array -> ["30 Days Of JavaScript"]
console.log(string.split(" ")); // Split to an array at space -> ["30", "Days", "Of", "JavaScript"]
let firstName = "Trishan";
console.log(firstName.split()); // Change to an array - > ["Trishan"]
console.log(firstName.split("")); // Split to an array at each letter -> ["T", "r", "i", "s", "h", "a", "n"]
let countries = "Finland, Sweden, Norway, Denmark, and Iceland";
console.log(countries.split(",")); // split to any array at comma -> ["Finland", " Sweden", " Norway", " Denmark", " and Iceland"]
console.log(countries.split(", ")); // ["Finland", "Sweden", "Norway", "Denmark", "and Iceland"]
let string = " 30 Days Of JavaScript ";
console.log(string); // 30 Days Of JavasCript
console.log(string.trim()); //30 Days Of JavasCript
let firstName = " Trishan ";
console.log(firstName); // Trishan
console.log(firstName.trim()); //Trishan
let string = "30 Days Of JavaScript";
console.log(string.includes("Days")); // true
console.log(string.includes("days")); // false - it is case sensitive!
console.log(string.includes("Script")); // true
console.log(string.includes("script")); // false
console.log(string.includes("java")); // false
console.log(string.includes("Java")); // true
let country = "Nepal";
console.log(country.includes("nep")); // false
console.log(country.includes("Nep")); // true
console.log(country.includes("pa")); // true
console.log(country.includes("da")); // false
string.replace(oldsubstring, newsubstring);
let string = "30 Days Of JavaScript";
console.log(string.replace("JavaScript", "Python")); // 30 Days Of Python
let country = "Finland";
console.log(country.replace("Fin", "Noman")); // Nomanland
string.charAt(index);
let string = "30 Days Of JavaScript";
console.log(string.charAt(0)); // 3
let lastIndex = string.length - 1;
console.log(string.charAt(lastIndex)); // t
string.indexOf(substring);
let string = "30 Days Of JavaScript";
console.log(string.indexOf("D")); // 3
console.log(string.indexOf("Days")); // 3
console.log(string.indexOf("days")); // -1
console.log(string.indexOf("a")); // 4
console.log(string.indexOf("JavaScript")); // 11
console.log(string.indexOf("Script")); //15
console.log(string.indexOf("script")); // -1
string.concat(substring, substring, substring);
let string = "30";
console.log(string.concat("Days", "Of", "JavaScript")); // 30DaysOfJavaScript
let country = "Nep";
console.log(country.concat("al")); // Nepal
//syntax
string.startsWith(substring);
let string = "Love is the best to in this world";
console.log(string.startsWith("Love")); // true
console.log(string.startsWith("love")); // false - it is case sensitive!
console.log(string.startsWith("world")); // false
let country = "Nepal";
console.log(country.startsWith("Nep")); // true
console.log(country.startsWith("al")); // false
console.log(country.startsWith("epal")); // false
string.endsWith(substring);
let string = "Love is the most powerful feeling in the world";
console.log(string.endsWith("world")); // true
console.log(string.endsWith("love")); // false
console.log(string.endsWith("in the world")); // true
let country = "Nepal";
console.log(country.endsWith("pal")); // true
console.log(country.endsWith("Nep")); // false
console.log(country.endsWith("ep")); // false
To check the data type of a certain variable we use the typeof method.
Example:
// Different javascript data types
// Let's declare different data types
let firstName = "Trishan"; // string
let lastName = "Wagle"; // string
let country = "Nepal"; // string
let city = "Kathmandu"; // string
let age = 17; // number, it is not my real age, do not worry about it
let job; // undefined, because a value was not assigned
console.log(typeof "Trishan"); // string
console.log(typeof firstName); // string
console.log(typeof 10); // number
console.log(typeof 3.14); // number
console.log(typeof true); // boolean
console.log(typeof false); // boolean
console.log(typeof NaN); // number
console.log(typeof job); // undefined
console.log(typeof undefined); // undefined
console.log(typeof null); // object
We can convert string number to a number. Any number inside a quote is a string number. An example of a string number: ‘10’, ‘5’, etc. We can convert string to number using the following methods:
let num = "10";
let numInt = parseInt(num);
console.log(numInt); // 10
We can convert string float number to a float number. Any float number inside a quote is a string float number. An example of a string float number: ‘9.81’, ‘3.14’, ‘1.44’, etc. We can convert string float to number using the following methods:
let num = "9.81";
let numFloat = parseFloat(num);
console.log(numFloat); // 9.81
We can convert float numbers to integers. We use the following method to convert float to int:
let num = 9.81;
let numInt = parseInt(num);
console.log(numInt); // 9
🌕 You are awesome. You have just completed day 1 of 30 days JS and you are one step ahead on your way to greatness. Now do some exercises on your own for your brain and for your muscle memory too. #happy_learning