JavaScript, Variables, Rules, Data Types, Typeof Conversion, Arithmetic Operators, Ternary Operators, Input & Output
JavaScript
JavaScript is a high-level, interpreted programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. From a web development perspective, JavaScript enables dynamic and interactive elements on web pages, making it an essential tool for modern web development.
Client-Side Scripting:
- JavaScript primarily runs in the browser, allowing developers to create interactive web pages. This means users can interact with the page in real-time without needing to reload it.
DOM Manipulation:
- JavaScript can manipulate the Document Object Model (DOM) of a web page, which represents the structure of the document. This manipulation allows developers to dynamically update content, structure, and styling based on user actions or other conditions.
Event Handling:
- JavaScript is designed to handle events such as clicks, mouse movements, and key presses. This event-driven programming model is crucial for creating responsive and interactive user interfaces.
AJAX and Fetch API:
- JavaScript enables asynchronous communication with servers through technologies like AJAX (Asynchronous JavaScript and XML) and the Fetch API. This allows web pages to request and receive data from servers without needing to reload, leading to a smoother user experience.
Frameworks and Libraries:
- JavaScript has a rich ecosystem of frameworks and libraries such as React, Angular, and Vue.js, which simplify the development of complex web applications by providing pre-built components and structured patterns.
Server-Side Development:
- With the advent of Node.js, JavaScript is not limited to the client-side. Node.js allows JavaScript to be used for server-side programming, enabling developers to use a single language for both client and server sides of web applications.
Variables
In Javascript there were two types of variable declarations were available: var
and const
. But In 2015 JavaScript introduced ES6 (ECMAScript) Where they decapitated var
and introduced let
with much more re-usability. Each has different properties and use cases. Here's a breakdown of each:
var
Scope: Function-scoped. Variables declared with
var
are accessible throughout the function in which they are declared.Hoisting: Variables declared with
var
are hoisted to the top of their scope and initialized withundefined
.Re-declaration: Can be re-declared within the same scope without error.
Usage: Generally considered outdated and is less recommended in modern JavaScript due to its function-scoping and hoisting behavior which can lead to bugs and unexpected behavior.
var a = 10;
console.log(a); // 10
console.log();
is a function to print out our values in our terminal to check how our variables or anything else is behaving like.We declared that our
a
var will have a value of 10 (in Numbers) and while logging it we got the value 10 in terminal from oura
variable.
var b = 24;
console.log(b); //24
b = 20; //Updating our variable with new value.
console.log(b); //We got our updated value, 20.
- As we have discussed earlier that
var
has been decapitated now, and replaced it withlet
, we should now follow this rule and never touchvar
again.
let
Scope: Block-scoped. Variables declared with
let
are accessible only within the block (enclosed by{}
) in which they are declared.Hoisting: Variables declared with
let
are hoisted to the top of their block but are not initialized, leading to a "temporal dead zone" until the declaration is encountered.Re-declaration: Cannot be re-declared within the same scope.
Usage: Preferred for variables that will be reassigned, and for maintaining proper block-scoping.
let firstName = "Aquib";
console.log(firstName); //"Aquib"
- We declared that our
c
let will have a value of "Aquib" (in Strings) and while logging it we got the value "Aquib" in terminal from ourc
variable.
let lastName = "ali";
console.log(lastName); //"ali"
//Updating my firstName variable -
firstName = "aquib";
console.log(firstName + lastName); //"aquibali"
//We can play a little more with this.
console.log(firstName + " " + lastName); //"aquib ali
On the second log we joint our two Strings into one String, but there were no space in between my first and last name.
On the third log we joint three Strings, first as my firstName variable, second as a manual declaration String with one space inside it, third as my lastName variable. Now my name here looks perfect.
what will happen if I join two number variables together? Let's look at it.
let num1 = "5";
let num2 = "6";
console.log(num1 + num2); //56
You will wonder why is it behaving like this? Can it not do basic calculations? Well no it can do all sorts of calculations but its all about how you are declaring your values in the variable.
Our type of these variables are not Numbers, they are still Strings, that is why instead of calculating the values its only joining both Strings into one.
//Updating our num1 and num2 variables -
num1 = 5;
num2 = 6;
console.log(num1 + num2); //11
- Now this time we declared a Number type of variable, that is why it was able to understand that it is a number and it has to perform a calculation now.
const
Scope: Block-scoped, similar to
let
.Hoisting: Variables declared with
const
are hoisted to the top of their block but are not initialized, leading to a "temporal dead zone" until the declaration is encountered.Re-declaration: Cannot be re-declared within the same scope.
Reassignment: Cannot be reassigned once declared. The value must be assigned at the time of declaration.
Usage: Preferred for variables that should not be reassigned, providing clear intent that the variable is meant to remain constant.
const dateOfBirth = "16/10/2002";
console.log(dateOfBirth); //"16/10/2002"
- You might be wondering why we have another variable named as
const
now? As you have read so far that it is a constant variable. Once declared we cannot update its values.
dateOfBirth = "17/10/2002";
console.log(dateOfBirth); //TypeError: Assignment to constant variable.
- As you can see, it has thrown us an error.
As a beginner you might be thinking our variables should always be in a way that we can update it again in future, but you are wrong. We always try to make a constant variable so that in future it cannot be changed again in future, a secure proof logic's.
Rules for Naming Variables
Starts with a Letter, Underscore, or Dollar Sign:
A variable name must begin with a letter (a-z or A-Z), an underscore (_), or a dollar sign ($).
Example:
let name;
,let _private;
,let $dollar;
Cannot Start with a Number:
A variable name cannot begin with a number.
Example:
let 1stName;
is invalid, whilelet first1Name;
is valid.
Subsequent Characters Can Include Letters, Numbers, Underscores, or Dollar Signs:
After the first character, variable names can include letters, digits, underscores, or dollar signs.
Example:
let name1;
,let user_name;
,let $variable123;
Case-Sensitive:
JavaScript is case-sensitive, meaning
let name;
andlet Name;
are considered two different variables.Example:
let myVar;
andlet myvar;
are different variables.
Keywords Cannot Be Used as Variable Names:
You cannot use JavaScript reserved keywords as variable names. These include words like
let
,const
,var
,function
,return
,if
,else
,for
,while
,switch
,case
,default
,break
,continue
, and many others.Example:
let function;
is invalid.
// Valid variable names
let name;
let _name;
let $name;
let name1;
let user_name;
let $variable123;
// Invalid variable names
let 1stName; // Starts with a number
let user-name; // Contains a hyphen
let let; // Uses a reserved keyword
- Here's a list of JavaScript reserved keywords -
abstract
arguments
await
boolean
break
byte
case
catch
char
class
const
continue
debugger
default
delete
do
double
else
enum
eval
export
extends
false
final
finally
float
for
function
goto
if
implements
import
in
instanceof
int
interface
let
long
native
new
null
package
private
protected
public
return
short
static
super
switch
synchronized
this
throw
throws
transient
true
try
typeof
var
void
volatile
while
with
yield
- No need to memorize all of the keywords, as you will be studying in-depth you will understand it automatically.
Data Types
JavaScript has a variety of data types, Each of them has their own use.
Number
Represents both integer and floating-point numbers.
let age = 25;
let price = 99.99;
String
Represents textual data enclosed in single quotes ('
), double quotes ("
), or backticks (`
) for template literals.
let name = 'John';
let greeting = "Hello";
let message = greeting, `${name}`;
Boolean
- Represents logical values:
true
orfalse
.
let isActive = true;
let isMember = false;
Undefined
Represents a variable that has been declared but not yet assigned a value.
let x;
console.log(x); // undefined
let x = undefined;
console.log(x); //undefined
Null
- Represents the intentional absence of any object value.
let user = null;
console.log(user); //null
Typeof conversion
The typeof()
function is useful when we are not sure what type of data type our variable is.
let z = 30;
console.log(typeof(z)); //Number
Type conversion
Type conversion in JavaScript, also known as type coercion, can happen either implicitly or explicitly. Let us go through this in a little depth to see how it works:
Boolean Conversion:
JavaScript considers
0
asfalse
and all non-zero numbers astrue
.When
true
is converted to a number, the result is always1
.
String Conversion:
- The
String()
function convertsnull
andundefined
to strings.
Falsy and Truthy Values:
The following values are considered as false
in JavaScript
undefined
null
0
NaN
''
(empty string)
All other values are considered as true
.
Here are some examples using Type conversion:
- Boolean
console.log(Boolean(0)); // false
console.log(Boolean(1)); // true
console.log(Boolean(-1)); // true
console.log(Number(true)); // 1
console.log(Number(false)); // 0
- String
console.log(String(null)); // "null"
console.log(String(undefined)); // "undefined"
console.log(String(123)); // "123"
console.log(String(true)); // "true"
- Falsy and Truthy Values
//falsy
console.log(Boolean(undefined)); // false
console.log(Boolean(null)); // false
console.log(Boolean(0)); // false
console.log(Boolean(NaN)); // false
console.log(Boolean('')); // false
//truthy
console.log(Boolean('Hello')); // true
console.log(Boolean(42)); // true
console.log(Boolean([])); // true (empty array)
console.log(Boolean({})); // true (empty object)
console.log(Boolean(function() {})); // true (function)
Explicitly Type Conversion
To Boolean
- You can use the
Boolean()
function to explicitly convert a value to a Boolean.
let isFalse = 0;
let isTruth = 1;
console.log(Boolean(isFalse)); // false
console.log(Boolean('')); // false
console.log(Boolean(isTruth)); //true
console.log(Boolean("hello")) //true
To Number
- Use the
Number()
function for explicit conversion to a number.
console.log(Number('123')); // 123
console.log(Number('123abc')); // NaN
console.log(Number(true)); // 1
console.log(Number(false)); // 0
To String
- Use the
String()
function or template literals for explicit conversion to a string.
console.log(String(123)); // "123"
console.log(String(true)); // "true"
console.log(`Value: ${123}`); // "Value: 123"
Implicit Type Conversion
In Boolean Contexts
- JavaScript automatically converts values to Boolean in logical operations and control structures.
if (0) {
console.log('This will not run');
}
if (1) {
console.log('This will run');
}
In Mathematical Operations
- JavaScript converts strings and other types to numbers when performing mathematical operations.
console.log('5' - 3); // 2
console.log('5' + 3); // "53" (string concatenation)
console.log('5' * 2); // 10
console.log('5' / 2); // 2.5
In String Contexts
- JavaScript converts values to strings when using the
+
operator with a string.
console.log('The answer is ' + 42); // "The answer is 42"
console.log('Value: ' + true); // "Value: true"
Arithmetic Operators
JavaScript provides a variety of arithmetic operators for performing mathematical operations. Here's a comprehensive overview of these operators, including both basic arithmetic operators and more specific ones like increment, decrement, and exponentiation.
Basic Arithmetic Operators
Addition (
+
)- Adds two numbers.
let sum = 5 + 3; // 8
Subtraction (
-
)- Subtracts the right operand from the left operand.
let difference = 5 - 3; // 2
Multiplication (
*
)- Multiplies two numbers.
let product = 5 * 3; // 15
Division (
/
)- Divides the left operand by the right operand.
let quotient = 15 / 3; // 5
Modulus (
%
)- Returns the remainder of the division of the left operand by the right operand.
let remainder = 5 % 3; // 2
Exponentiation (
**
)- Raises the left operand to the power of the right operand.
let power = 5 ** 3; // 125
Increment and Decrement Operators
Increment (
++
)Increases an integer value by one.
Can be used as a prefix or postfix operator.
let x = 5;
x++; // Postfix: x is now 6
++x; // Prefix: x is now 7
Decrement (
--
)Decreases an integer value by one.
Can be used as a prefix or postfix operator.
let y = 5;
y--; // Postfix: y is now 4
--y; // Prefix: y is now 3
Equality Operators
Equality (
==
)- Compares two values for equality after performing type conversion.
console.log(5 == '5'); // true (type coercion occurs)
console.log(0 == false); // true (type coercion occurs)
Strict Equality (
===
)- Compares two values for equality without performing type conversion. Both the value and the type must be the same.
console.log(5 === '5'); // false (no type coercion)
console.log(0 === false); // false (no type coercion)
console.log(5 === 5); // true
Comparison Operators
Greater than (
>
)- Returns
true
if the left operand is greater than the right operand.
- Returns
console.log(5 > 3); // true
Less than (
<
)- Returns
true
if the left operand is less than the right operand.
- Returns
console.log(5 < 3); // false
Greater than or equal to (
>=
)- Returns
true
if the left operand is greater than or equal to the right operand.
- Returns
console.log(5 >= 5); // true
Less than or equal to (
<=
)- Returns
true
if the left operand is less than or equal to the right operand.
- Returns
console.log(5 <= 3); // false
Here are some examples using Arithmetic Operators:
// Addition
let sum = 10 + 5;
console.log(sum); // 15
// Subtraction
let difference = 10 - 5;
console.log(difference); // 5
// Multiplication
let product = 10 * 5;
console.log(product); // 50
// Division
let quotient = 10 / 5;
console.log(quotient); // 2
// Modulus
let remainder = 10 % 3;
console.log(remainder); // 1
// Exponentiation
let power = 2 ** 3;
console.log(power); // 8
// Increment
let counter = 0;
counter++;
console.log(counter); // 1
// Decrement
counter--;
console.log(counter); // 0
// Equality and Strict Equality
console.log(5 == '5'); // true
console.log(5 === '5'); // false
console.log(5 === 5); // true
Understanding and using these arithmetic and comparison operators correctly is fundamental to programming in JavaScript. While ==
can be useful, it's generally safer to use ===
to avoid unexpected results due to type coercion. The increment (++
) and decrement (--
) operators are handy for loops and counters, and the exponentiation operator (**
) provides a straightforward way to handle powers in mathematical operations.
Operators & Operands
In programming, operators and operands are fundamental concepts used to perform calculations and other operations on data.
Operators
Operators are special symbols or keywords that are used to perform operations on operands. They define the type of operation to be performed on the data. +
(addition), -
(subtraction), *
(multiplication), /
(division), %
(modulus), **
(exponentiation), =
(assignment), +=
(addition assignment), -=
(subtraction assignment), *=
(multiplication assignment), /=
(division assignment), %=
(modulus assignment), ==
(equal to), ===
(strict equal to), !=
(not equal to), !==
(strict not equal to), >
(greater than), <
(less than), >=
(greater than or equal to), <=
(less than or equal to), &&
(logical AND), ||
(logical OR), !
(logical NOT), ++
(increment) and --
(decrement) are Operators.
Operands
Operands are the values or variables on which the operators perform the operations. They are the entities being manipulated and processed by the operators. The words or keywords you will be writing before an operator and after an operator are called as operands.
let d = a + b;
//(a) operand, (+) operator and (b) operand
Ternary Operators
If-Else Statements
The if-else
statement is used to execute code based on a condition. If the condition evaluates to true
, the code inside the if
block is executed; otherwise, the code inside the else
block is executed.
Syntax:
if (condition) {
// code to run if condition is true
} else {
// code to run if condition is false
}
let age = 10;
if (age > 25) {
console.log('You can drive');
} else {
console.log('You cannot drive');
} //Output: 'You cannot drive'
Here the age is smaller than our condition 25, so it will throw 'You cannot drive'. If the age was bigger than our condition then it would have thrown 'You can drive.' .
Else-If Statements
The else-if
statement is used when you have multiple conditions to check. It allows you to test a series of conditions until one is found to be true
.
Syntax:
if (condition1) {
// code to run if condition1 is true
} else if (condition2) {
// code to run if condition2 is true
} else {
// code to run if none of the above conditions are true
}
let score = 85;
if (score >= 90) {
console.log('Grade: A');
} else if (score >= 80) {
console.log('Grade: B');
} else if (score >= 70) {
console.log('Grade: C');
} else if (score >= 60) {
console.log('Grade: D');
} else {
console.log('Grade: F');
}
Ternary Operator
The ternary operator is a shorthand for the if-else
statement that allows you to write conditional expressions in a compact form. It's also known as the conditional operator. The syntax is:
Syntax:
condition ? expressionIfTrue : expressionIfFalse
let age = 18;
let canVote = (age >= 18) ? 'Yes' : 'No';
console.log(canVote); //Output: "Yes"
Switch Statements
The switch
statement is used to perform different actions based on different conditions. It is an alternative to using multiple else-if
statements.
Syntax:
switch (expression) {
case value1:
// code to run if expression === value1
break;
case value2:
// code to run if expression === value2
break;
// add more cases as needed
default:
// code to run if no cases match
}
let day = 3;
let dayName;
switch (day) {
case 1:
dayName = 'Monday';
break;
case 2:
dayName = 'Tuesday';
break;
case 3:
dayName = 'Wednesday';
break;
case 4:
dayName = 'Thursday';
break;
case 5:
dayName = 'Friday';
break;
case 6:
dayName = 'Saturday';
break;
case 7:
dayName = 'Sunday';
break;
default:
dayName = 'Invalid day';
}
console.log(dayName); // Output: "Wednesday"
Logical Operators
Logical operators are used to combine multiple conditions. The most common logical operators are:
AND (
&&
): Returnstrue
if both operands aretrue
.OR (
||
): Returnstrue
if at least one of the operands istrue
.NOT (
!
): Returnstrue
if the operand isfalse
, and vice versa.
AND (&&
):
let age = 25;
let hasID = true;
if (age >= 18 && hasID) {
console.log('Allowed to enter.');
} else {
console.log('Not allowed to enter.');
}
OR (||
):
let isWeekend = true;
let isHoliday = false;
if (isWeekend || isHoliday) {
console.log('No need to go to work.');
} else {
console.log('Need to go to work.');
}
NOT (!
):
let isRaining = false;
if (!isRaining) {
console.log('Go for a walk.');
} else {
console.log('Stay indoors.');
}
Input & Output
We don't really have to take any data directly from our JavaScript but we should know these functions for our better knowledge level.
Output Methods
alert()
:
- Displays a pop-up alert box with a message.
alert('This is an alert box!');
Input Methods
prompt()
:
- Displays a dialog box that prompts the user for input.
let name = prompt('Enter your name:');
console.log('Hello, ' + name);
Having a deep understanding of basic JavaScript is essential, otherwise everything will start to create confusion inside our head, doing enough practice everyday will make your basic understanding stronger.
Subscribe to my newsletter
Read articles from Syed Aquib Ali directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Syed Aquib Ali
Syed Aquib Ali
I am a MERN stack developer who has learnt everything yet trying to polish his skills 🥂, I love backend more than frontend.