JavaScript fundamentals: Variables and Data types
A variable is a container in which we assign a value to for storage.
Rules of naming variables
Starts with a lowercase letter.
Has no spaces and uses camelCasing eg myLuckyNumber
Does not use reserved words.
Datatypes
a) Primitive data types
111.1
1
"This is a string"
`This is also a string`
'This is another string'
""
Numbers, Strings, Booleans, Undefined, Symbol, Null
b)Structured
Objects, Functions
Numbers: JavaScript provides a numeric data type for working with numerical values, including integers and floating-point numbers. For example:
let quantity = 10;
let price = 19.99;
let total = quantity * price;
console.log("Total: $" + total.toFixed(2));
In this example, we declare variables to store quantity and price. We then perform a calculation to determine the total cost by multiplying the two variables. The toFixed()
method ensures that the total is displayed with two decimal places.
Strings: Strings are used to represent textual data. They are enclosed within single quotes (‘’) or double quotes (“”) in JavaScript. For example:
let message = "Hello, World!";
let name = "John";
console.log(message + " My name is " + name + ".");
In this example, we declare a message variable with a greeting and a name variable with a person’s name. We then concatenate these variables and output the combined message using the +
operator.
Booleans: Booleans are either true or false. They are used for logical operations, conditional statements, and decision-making. For example:
let isLogged = true;
let isAdmin = false;
if (isLogged) {
console.log("User is logged in.");
}
if (!isAdmin) {
console.log("User is not an admin.");
}
In this example, we declare variables to represent whether a user is logged in (isLogged
) and whether they have admin privileges (isAdmin
). We use conditional statements (if
) to check the boolean values and output corresponding messages based on the conditions.
Undefined: When a variable is declared but not assigned a value, it is undefined. For example:
let firstName;
console.log(firstName); // Output: undefined
In this example, we declare a variable firstName
but don't assign any value to it. When we output the variable, it returns undefined since it doesn't have a defined value.
Null: Null represents the intentional absence of any object value. For example:
let userDetails = null;
console.log(userDetails); // Output: null
In this example, we assign the value null to the variable userDetails
, indicating that there is no user information available.
Symbol: Symbols are unique and immutable data types introduced in ECMAScript 6. For example:
const id = Symbol("id");
const user = {
[id]: "abc123",
name: "John Doe",
};
console.log(user[id]); // Output: abc123
In this example, we create a symbol id
and use it as a key in an object. Symbols are often used as unique identifiers to avoid naming conflicts.