Introduction:
JavaScript is a high-level interpreted, object-oriented programming language created to make web pages alive.
It was created by Brenda Eich of Netscape in 1995.
JavaScript is an Interpreted language, whereas C++, Rust and Java are Compiled languages.
Compiled vs Interpreted:
Compiled | Interpreted |
---|---|
Firstly, we need to compile, and then we can run. | Usually, in interpreted it runs line by line. |
Here, it doesn’t compile if there is an error in the code | It will run partially if the error occurs later |
Write your First JavaScript Program:
So, we will write our first JavaScript program before we learn the fundamentals. For this open your browser and open google.com now right click on the tab and you will see an option called Inspect which I have shown below click on that:
Now you will see a pop-up open on the right side and in that, you will see a tab called console click on that your browser console will now be opened. In that write the JavaScript Program as I shown in below and press enter and your code will be logged..!
Congrats you just wrote your JavaScript code..!🎉🥳🥳
Writing our first JavaScript code in the browser console will always be fun and exciting.
Variables:
In JavaScript, variables can be declared in 4 ways:-
Automatically
var
let
const
Automatically
It means we can directly declare variables, but they are considered as Undeclared variables.
x = 4;
y = 2;
z = x + y;
Remember, in this way, it is not a good practice.
var
It is a variable that defines the value, and it is used whenever we don't want to change the value. It is used in all JavaScript code from 1995 to 2015.
var a = 10;
var b = 15;
let
let is also a variable to define the value and it is used whenever we want to change the value. This “let” keyword was added to JavaScript in 2015.
let firstName = "Monkey D";
let lastName = "Luffy";
const
It means constant, we cannot change the value once it is defined as const, if we try to change it throws the error. This “const” keyword was also added to JS in 2015.
const age = 24;
age = 40 // throws error.
Learn to write Comments:
Comments can be used to explain the code, and it makes users to more easily readable.
// This is a single-line comment
/*
This is a multi-line comment
*/
DataTypes:
There are several data types in JavaScript
String
Number
Boolean
BigInt
Object
Undefined
Null
// String Example
let FirstName = "Goku";
// Number Example
let num = 45;
// Boolean Example
let isLoggedIn = false;
// BigInt Example
let x = BigInt("123456789012345678901234567890");
// Arrays
let arr = [35, 38, 14, 75, 8];
// Object
let user = {
firstName: "Pavan",
lastName: "Varma",
age: 24,
};
Now, we gonna take about Primitives and Non-Primitives,
In simple terms, we say that Primitives are gonna stored in the stack and Non-Primtives are stored in Heap.
// Primitives Example
let num = 20;
console.log(typeof num); // Number
let name = "Pavan";
console.log(typeof name); // String
let isTrue = true;
console.log(typeof isTrue); // Boolean
let firstName; // Null
let lastName;
console.log(lastName); // undefined
const sm1 = Symbol("Pavan");
console.log(sm1); // Symbol
// Non-Primitives Example
let userName = {
firstName: "Pavan",
isLoggedIn: true,
};
console.log(userName.firstName);
console.log(userName.lastName);
console.log(typeof userName); // Object
let arr = ["a", "pavan", "JavaScript", "HTML", "CSS", true]; // array object
Operators:
Most of us already know about what are the different operators, because mostly in every programming language the operators are the same.
Assignment operator (=, +=, -=, *=, ?=).
Comparison operators (>, >=, <, <=, !, !=, ==, ===)
Arithmetic operators (+, -, , /, %, **, ++, - -)
Logical operators (&&, ||, !)
I will show some of the operator examples, hope you can practice them in your code editor.
let addition = 4 + 5;
let subtraction = 9 - 3;
let mul = 3 * 5;
let div = 8 / 2;
let remainder = 9 % 2;
let expo = 2 ** 4; // 2 ^ 4
let myScore = 110;
myScore++; // 111
let credits = 25;
credits--; // 24
// Comparison operator
let num1 = 3;
let num2 = 3;
let num3 = 6;
console.log(num1 == num2);
console.log(num1 != num3);
console.log(num1 > num3);
console.log(num1 < num3);
// Logical operators
let isLoggedIn = true;
let isPaid = false;
console.log(isLoggedIn && isPaid);
let isEmailUser = true;
let isGoogleUser = false;
console.log(isEmailUser || isGoogleUser);
Conditions:
Conditional statements perform different actions based on different conditions. For example, if we want to execute a code only if some condition is “true,” we will use conditional statements.
// Syntax
if(condition) {
// block of code to be executed if the condition is true;
} else {
// this block of code executes when the if(condition) is not true;
}
Now we understand how conditions we do an example program,
//Check if a number is greater than another number:
let num1 = 5;
let num2 = 10;
if (num1 > num2) {
console.log("num1 is greater than num2");
} else {
console.log("Nope, num1 is not greater");
}
I will mention some challenges if you’re interested, do solve those and if you solved all of them mention
“I Solved all the Conditional Challenges” in the comments :)
Check if a string is equal to another string.
Check if a variable is a number or not.
Check if a boolean value is true or false.
Check if an array is empty or not.
Loops:
What is Loops? So if we want to run a code over again and again, we use loops :)
JavaScript Supports different kinds of Loops:
for - if we know how many times our loop iterates then we will use for loop
for/in - loops through the properties of an object
for/of - loops through the values of an iterable object
forEach - this loop is used to iterate through the array
while - if we don’t know how many times our loop iterates then we
will use the while loopdo while - if we want our code to be executed at least one time
even if our condition is false then we use this.
// for loop syntax
for (expression 1; expression 2; expression 3) {
// code block to be executed
}
// for-in syntax
for (key in object) {
// code block to be executed
}
// for-of syntax
for (variable of iterable) {
// code block to be executed
}
// forEach syntax
array.forEach(() => {
// code block
)};
// while syntax
while(condition) {
// block of code to execute
}
// do-while syntax
do{
// block of code to execute
} while(condition)
Now, we will see some examples of these loops mentioned above,
/*
1. Write a 'for' loop that loops through the array ["green tea", "black tea", "chai", "oolong tea"].
and stops the loop when it finds "chai".
Store all teas before "chai" in a new array named 'selectedTrees'
*/
let teaName = ["green tea", "black tea", "chai", "oolong tea"];
let selectedTrees = [];
for (let i = 0; i < teaName.length; i++) {
if (teaName[i] === "chai") {
break;
}
selectedTrees.push(teaName[i]);
}
console.log(selectedTrees);
/*
2. Write a 'while' loop that calculates the sum of all numbers from 1 to 5 and stores the
result in a variable called 'sum'.
*/
let num = 1;
let sum = 0;
// 1+2+3+4+5
while (num <= 5) {
sum += num;
num++;
}
console.log(sum);
/*
3. Write a 'do while' loop that prompts a user to enter their favorite tea type until they enter 'stop'
store each tea type in an array named 'teaCollection'.
*/
let teaCollection = [];
let tea;
do {
// tea = prompt("Enter you favorite tea (type 'stop' to finish)");
if (tea != "stop") {
teaCollection.push(tea);
}
} while (tea !== "stop");
/*
4. Use a 'for-of' loop to iterate through the array [1, 2, 3, 4, 5] and stop the number '4' is found.
store the numbers before '4' in an array named 'smallNumbers'
*/
let num = [1, 2, 3, 4, 5];
let smallNumbers = [];
for (const n of num) {
if (n == 4) {
break;
}
smallNumbers.push(n);
}
console.log(smallNumbers);
/*
5. Use a 'for-in' loop to loop through an object containing city populations .
stop the loop when the population of "berlin" is found and store all previous cities populations
in a new object called 'cityPopulations'
*/
let citiesPopulation = {
London: 8900000,
"New York": 8400000,
Paris: 2200000,
Berlin: 3500000,
};
let cityPopulations = {};
for (const city in citiesPopulation) {
if (city == "Berlin") {
break;
}
cityPopulations[city] = citiesPopulation[city];
}
console.log(cityPopulations);
Challenges on Loops:
Write a 'for' loop that loops through the array ["london", "new
york", "paris", "berlin"] and skips "paris". Store the other cities
in a new array named 'visitedCities'.Use a 'for-of' loop to iterate through the array ["chai," "green
tea," "herbal tea," and "black tea"], skipping the "herbal tea."
Store the other teas in an array named 'preferredTeas.'Use a 'for-in' loop to loop through an object containing city
populations. skip any city with a population below 3 million and
store the rest in a new object named 'largeCities'.Write a 'forEach' loop that iterates through the array ['earl grey',
'green tea', 'chai', 'oolong tea']. Stop the loop when 'chai' is
found, and store all previous tea types in an array named
'availableTeas'.Write a 'while' loop that counts down from 5 to 1 and stores the
numbers in an array named 'countdown'.
Conclusion:
Yeah..! that’s it for this one, I hope you understand all the basics of JavaScript and in the next one we gonna talk about Arrays, Objects and their methods with different examples.
Some of the challenges are taken from the learnings that I taken to solve and I solved them and now on you. If you want to learn in YouTube I recommend you to watch Hitesh Sir Course
Hope You’re all doing well, Stay Hard..!
Code well and share your learnings in Public.
Top comments (0)