JavaScript 101: A Beginner's Guide to Types, Loops, Variables, and More
First step of "JavaScript Mastery Series"
What is JavaScript?
JavaScript is a powerful and versatile programming language that is widely used for web development. It is a high-level, interpreted language that allows you to create interactive and dynamic web pages.
In this blog post we will take a look at some of the key concepts in JavaScript, including types, comparisons, variables, conditionals, logical operators, functions, arrays, objects, and loops.
JavaScript Types
JavaScript has several built-in types that are used to represent different types of data. The most commonly used types are Number, String, Boolean, Undefined, Null, Symbol, and Object.
Number
Numbers in JavaScript can be integers or floating-point values. For example:
let age = 25;
let weight = 150.5;
String
Strings in JavaScript are used to represent text. They are enclosed in single or double quotes. For example:
let name = "John";
let message = 'Hello World!';
Boolean
Booleans in JavaScript represent true or false values. For example:
let isMarried = true;
let isStudent = false;
Undefined
A variable that has not been assigned a value is undefined. For example:
let x;
console.log(x); // undefined
Null
A variable that has been assigned the null value is considered to have no value. For example:
let y = null;
console.log(y); // null
Symbol
Symbols are a new feature in ECMAScript 6 and are used to create unique identifiers. For example:
let symbol1 = Symbol();
let symbol2 = Symbol();
console.log(symbol1 === symbol2); // false
Object
Objects in JavaScript are used to store collections of data. For example:
let user = {
name: "John",
age: 25,
hobby: "Soccer"
};
console.log(user.name); // "John"
console.log(user.age); // 25
console.log(user.hobby); // "Soccer"
JavaScript Comparisons
JavaScript provides several ways to compare values. The most commonly used comparisons are === (strict equality), !== (strict inequality), >= (greater than or equal to), <= (less than or equal to), > (greater than), and < (less than).
For example:
console.log(2 === 2); // true
console.log(2 !== 3); // true
console.log(5 >= 2); // true
console.log(5 <= 2); // false
console.log(5 > 2); // true
console.log(5 < 2); // false
JavaScript Variables
JavaScript provides several ways to declare variables. The most commonly used are var, let, and const.
var
Variables declared with var are function-scoped, which means they are only accessible within the function in which they are declared. For example:
var x = 5;
console.log(x); // 5
let
Variables declared with let are block-scoped, which means they are only accessible within the block in which they are declared. For example:
let y = 10;
console.log(y); // 10
const
const
is a new variable declaration in ECMAScript 6, similar to let
, but it cannot be reassigned after it's been declared. This makes it useful for situations where you want to prevent accidental reassignment of a variable. For example:
const pi = 3.14;
pi = 3; // this will throw an error
In short, const
is a new way to declare variables in JavaScript and it is used to create immutable variables that can't be reassigned.
JavaScript Condtionals
JavaScript provides several ways to control the flow of a program based on conditions. The most commonly used are if, else, else if, and switch.
if
The if statement is used to execute a block of code if a certain condition is true. For example:
let age = 25;
if (age >= 21) {
console.log("You are old enough to drink.");
}
else
The else statement is used to execute a block of code if the if statement's condition is not true. For example:
let age = 18;
if (age >= 21) {
console.log("You are old enough to drink.");
} else {
console.log("You are not old enough to drink.");
}
else if
The else if statement is used to check multiple conditions. For example:
let age = 25;
if (age >= 21) {
console.log("You are old enough to drink.");
} else if (age >= 18) {
console.log("You are old enough to vote.");
} else {
console.log("You are not old enough to do anything interesting.");
}
ternary
The ternary operator is a shorthand way of writing an if-else statement. For example:
let age = 25;
let canDrink = (age >= 21) ? "You are old enough to drink." : "You are not old enough to drink.";
console.log(canDrink);
switch
The switch statement is used to check multiple conditions. For example:
let grade = "A";
switch (grade) {
case "A":
console.log("Excellent job!");
break;
case "B":
console.log("Good job!");
break;
default:
console.log("Keep up the good work!");
}
JavaScript Logical Operators
JavaScript provides several logical operators to help control the flow of a program. The most commonly used are && (and), !! (not), and ! (not).
&& (and)
The && operator returns true if both conditions are true. For example:
let age = 25;
let isStudent = true;
if (age >= 21 && isStudent) {
console.log("You are old enough to drink and are a student.");
}
|| (or)
This operator returns the first truthy value among its operands. For example:
let a = true;
let b = false;
let c = "some text";
console.log(a || b); // Outputs: true
console.log(b || c); // Outputs: some text
console.log(a || c); // Outputs: true
! (not)
The ! operator negates a boolean value. For example:
let isStudent = true;
if (!isStudent) {
console.log("Not a student.");
} else {
console.log("Is a student.");
}
JavaScript Functions
JavaScript functions are blocks of code that can be executed multiple times. There are two ways to define a function in JavaScript:
// first way
var myFunction = function sayHello() {
console.log("Hello!");
}
myFunction(); // Outputs "Hello!"
// second way
function sayHello() {
console.log("Hello!");
}
sayHello(); // Outputs "Hello!"
Functions can also take parameters and return values. For example:
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // Outputs 5
Functions can also be defined as a property of an object, known as a method. For example:
let person = {
name: "John",
age: 25,
sayHello: function() {
console.log("Hello, my name is " + this.name + ".");
}
}
person.sayHello(); // Outputs "Hello, my name is John."
JavaScript Arrays
JavaScript arrays are used to store multiple values in a single variable. They are similar to objects, but with a length property and a set of array methods.
The most commonly used array methods are:
let list = ["tiger", "cat", "bear", "bird"];
// shift() method: Removes the first element from an array and returns it
let firstAnimal = list.shift();
console.log(firstAnimals); // Outputs: "tiger"
console.log(list); // Outputs: ["cat", "bear", "bird"]
// pop() method: Removes the last element from an array and returns it
let lastAnimals = list.pop();
console.log(lastAnimals); // Outputs: "bird"
console.log(list); // Outputs: ["cat", "bear"]
// push() method: Add one or more elements to the end of an array and returns the new length
let newLength = list.push("elephant");
console.log(newLength); // Outputs: 3
console.log(list); // Outputs: ["cat", "bear", "elephant"]
// concat() method: Merges two or more arrays and returns a new array
list = list.concat(["bee", "deer"])
console.log(list); // Outputs: ["cat", "bear", "elephant", "bee", "deer"]
//sort() method: Sorts the elements of an array in place and returns the array
list.sort();
console.log(list); // Outputs: ["bee", "bear", "cat", "deer", "elephant"]
JavaScript Objects
JavaScript objects are used to store key-value pairs of data. They are similar to arrays, but without a length property and with the ability to use any type of value as a key.
Objects can be defined using curly braces {} and properties can be added or modified using the dot notation or square brackets notation. For example:
let user = {
name: "John",
age: 34,
hobby: "Soccer",
isMarried: false
}
user.favouriteFood = "spinach";
console.log(user); // Outputs { name: "John", age: 34, hobby: "Soccer", isMarried: false, favouriteFood: "spinach" }
JavaScript Loops
JavaScript loops are used to execute a block of code multiple times. The most commonly used loops in JavaScript are:
for
loop through a block of code a specified number of times. For example:
let list = ["tiger", "cat", "bear", "bird"];
for (let i = 0; i < list.length; i++) {
list[i] = list[i] + "⭐";
}
console.log(list); // Outputs ["tiger⭐", "cat⭐", "bear⭐", "bird⭐"]
while
loop through a block of code while a specified condition is true. For example:
let counter = 0;
while (counter < 10) {
counter++;
}
console.log(counter); // Outputs 10
do while
loop through a block of code once and then repeat the loop while a specified condition is true. For example:
let counter = 0;
do {
counter++;
} while (counter < 10);
console.log(counter); // Outputs 10
for each
loop through an array and execute a function for each element. For example:
let list = ["tiger", "cat", "bear", "bird"];
list.forEach(function(animal) {
console.log(animal + "🔥");
});
// Outputs "tiger🔥", "cat🔥", "bear🔥", "bird🔥"
let list = ["tiger", "cat", "bear", "bird"];
list.forEach(function(animal, i) {
console.log(animal + " at index " + i);
});
// Outputs "tiger at index 0", "cat at index 1", "bear at index 2", "bird at index 3"
In conclusion, JavaScript is a powerful programming language that is widely used in web development. It provides a wide range of features such as variables, types, comparisons, conditionals, logical operators, functions, arrays, objects, and loops. By understanding these concepts, you can write efficient and effective code in JavaScript.
Summary 📖
The blog post explains the fundamental concepts of JavaScript, including types (Number, String, Boolean, Undefined, Null, Symbol, and Object), comparisons (!==, ===, >=, <=, >, <), variables (var, let, const), conditionals (if, else, else if, ternary, switch), logical operators (&&, !!, !), functions, arrays, objects, and loops (for, while, do-while, forEach).
It provides examples of each concept, demonstrating how they can be used in JavaScript programming. Overall, the article emphasizes that understanding these concepts is essential for writing efficient and effective code in JavaScript.
Thank You ❤️
Damn, you've reached this point 🥳👏. This shows that you are a keen learner🔥. Now do not stop here. There is much more to learn in JavaScript.
Writing blogs is not as simple as we think 🥲. It requires planning, resources, understanding and most importantly TIME🧑💻. I would be very much grateful if you could just share this blog post with your fellow peers (Linkedin, Facebook, Whatsapp, etc). Thank You Again❤️
Other Valuable Posts
All the basics you need to start working with Git