Basic JavaScript Syntax: Variables, Data Types, Operators, and Expressions
Welcome back! In this lesson, we will dive into the fundamentals of the JavaScript language, exploring basic syntax, data types, operators, and expressions.
Get ready to unravel the building blocks that will bring your scripts to life!
Variable
Declaration and Assignment
Imagine a cabinet with drawers. Each drawer is like a variable, where you store your belongings. To use a drawer, you first need to give it a name. This is where variable declaration comes in.
Example:
// Declaring a drawer called "name"
let name;
// Storing a value in the "name" drawer
name = "John";
Now that the “name” drawer is created and has a value stored, you can use it as many times as you want!
Assignment is like putting things into and taking things out of the drawer. You can:
- Assign an initial value:
let name = "John";
- Change the existing value:
name = "Mary";
- Perform operations and assign the result:
name = "Peter" + " Smith";
Dynamic typing means you don’t need to specify what type of thing you’re going to store in the drawer (text, number, etc.). JavaScript automatically understands by the value you put there.
Keywords for Declaration
There are three main ways to declare drawers in JavaScript:
var
: This is the oldest and least recommended way, as it can cause scope issues. Use with caution!let
: The recommended keyword for most situations. It allows redefinition within the same block, but not in external blocks.const
: Create permanent drawers with values that never change! Useconst
for constants like PI (3.14159) or your website name.
Variable Scope
Imagine drawers in different sections of the cabinet. Each section represents a variable scope.
- Block scope: Drawers within a section can only be used within that section. Variables declared with
let
orconst
have block scope. - Function scope: Drawers in the entire cabinet can be used within a function, but only while the function is executing. Variables declared with
var
generally have function scope.
Example:
// Outside the function, the variable "x" does not exist
console.log(x); // Error!
function example() {
// Inside the function, the variable "x" is created with block scope
let x = 10;
console.log(x); // 10
}
// Outside the function, the variable "x" no longer exists
console.log(x); // Error!
Rules for Variable Names
Start with: letter, underscore (), dollar sign ($).
Then use: letters, numbers, underscores (), dollar signs ($).
Do not use: JavaScript keywords.
Example:
Valid: let validVariable, _myName, $totalValue
Invalid: let 1number, function(), if
Data Types
Data Types in JavaScript
In JavaScript, data types are the basic elements that define the nature of the information you store and manipulate in your programs. Understanding them is crucial for writing robust and efficient JavaScript code.
Primitive Types:
- String: Represents sequences of characters, such as text:
"Hello, world!"
. - Number: Integer and decimal numbers, such as:
10
,3.14
. - Boolean: Logical values that can be
true
orfalse
. - Undefined: Indicates that a variable has not yet been assigned a value.
- Null: Represents the absence of a value, different from
undefined
. - Symbol: A special type for creating unique and immutable values, mainly used in advanced APIs.
Example of Primitive Type Declarations:
javascriptCopiar códigolet name = "John"; // String
let age = 30; // Number
let isOn = true; // Boolean
let price = undefined; // Undefined
let noValue = null; // Null
let symbol = Symbol("unique"); // Symbol
Objects:
- Group data and functionalities into a single block.
- Properties: Store information such as name, value, or function.
- Methods: Functions associated with the object that can be executed.
Example of Object Declaration:
javascriptCopiar códigolet person = {
name: "John",
age: 25,
speak: function() {
console.log("Hello!");
}
};
Arrays:
- Ordered lists of values.
- Can contain elements of any type, including other arrays.
- Access elements by index using square brackets ([]).
Example of Array Declaration:
javascriptCopiar códigolet fruits = ["Apple", "Banana", "Orange"];
console.log(fruits[1]); // Prints: Banana
Functions:
- Reusable blocks of code that perform specific tasks.
- Receive inputs (parameters) and can return values.
- Declared with the
function
keyword.
Example of Function Declaration:
javascriptCopiar códigofunction sum(x, y) {
return x + y;
}
let result = sum(5, 3);
console.log(result); // Prints: 8
Type Conversion:
- You can explicitly convert data types using functions like
parseInt()
,parseFloat()
,toString()
. - JavaScript also implicitly performs type coercion in some operations.
Important Tips:
- Use the appropriate data types for each situation.
- Pay attention to dynamic typing and avoid unnecessary conversions.
- Explore advanced features like Symbol and classes for more complex data structures.
Operators
Imagine you’re solving a puzzle and need to combine pieces to form the final picture. Operators in JavaScript work similarly, allowing you to manipulate values and perform operations on them.
Arithmetic Operators
These operators are used to perform mathematical operations.
They include addition (+), subtraction (-), multiplication (*), division (/), and the remainder operator (%).
We can think of these operators as puzzle pieces that help us calculate values and perform calculations.
Operator | Description | Example |
---|---|---|
+ | Addition | 5 + 3 = 8 |
– | Subtraction | 5 – 3 = 2 |
* | Multiplication | 5 * 3 = 15 |
/ | Division | 6 / 3 = 2 |
% | Remainder | 7 % 3 = 1 |
Assignment Operators
These operators are used to assign values to variables. The basic assignment operator is the equals sign (=), which assigns a value to the variable.
For example, x = 5 assigns the value 5 to the variable x. Additionally, there are combined assignment operators like +=, -=, *=, and /=, which perform the mathematical operation and assign the result to the variable.
Operator | Description | Example |
---|---|---|
= | Assignment | x = 5 |
+= | Addition and Assignment | x += 3 (x = x + 3) |
-= | Subtraction and Assignment | x -= 3 (x = x – 3) |
*= | Multiplication and Assignment | x *= 3 (x = x * 3) |
/= | Division and Assignment | x /= 3 (x = x / 3) |
Comparison Operators
These operators are used to compare values and return a boolean value (true or false).
They include equality operators (==, ===), inequality operators (!=, !==), comparison operators (<, >, <=, >=), and logical operators (&&, ||).
We can think of these operators as pieces that help us check if two puzzle pieces fit together or if one is larger than the other.
Operator | Description | Example |
---|---|---|
== | Equal | 5 == “5” (true) |
=== | Strictly Equal | 5 === “5” (false) |
!= | Not Equal | 5 != “5” (false) |
!== | Strictly Not Equal | 5 !== “5” (true) |
> | Greater Than | 5 > 3 (true) |
< | Less Than | 5 < 3 (false) |
>= | Greater or Equal Than | 5 >= 5 (true) |
<= | Less or Equal Than | 5 <= 3 (false) |
Logical Operators
These operators are used to combine boolean values and return a boolean result.
Logical operators include the logical NOT (!), logical AND (&&), and logical OR (||).
We can think of these operators as pieces that help us combine different parts of the puzzle to get a final answer.
Operator | Description | Example |
---|---|---|
! | Logical NOT | !true (false) |
&& | Logical AND | true && false (false) |
Increment and Decrement Operators
These operators are used to increase or decrease the value of a variable by one unit.
The increment operator (++) increases the value by 1, while the decrement operator (–) decreases the value by 1.
We can think of these operators as pieces that allow us to move to the next or previous puzzle piece.
Operator | Description | Example |
---|---|---|
++ | Increment | x++ (x = x + 1) |
— | Decrement | x– (x = x – 1) |
Concatenation Operators
These operators are used to join or combine strings. The concatenation operator (+) allows us to join multiple strings into a single string.
We can think of this operator as the piece that helps us form complete sentences by joining words.
Operator | Description | Example |
---|---|---|
+ | String Concatenation | “Hello” + “World” (“HelloWorld”) |
Expressions
Expressions in JavaScript
Expressions are like the basic units of code that combine values, variables, operators, and literals to perform calculations, comparisons, assignments, and other operations. They are the foundation for building more complex code blocks and form the logical structure of your programs.
Types of Expressions in JavaScript:
- Arithmetic Expressions: Perform basic mathematical operations such as addition, subtraction, multiplication, division, and exponentiation. Example:
2 + 3 * 5
. - Relational Expressions: Compare values, resulting in logical values
true
orfalse
. Example:x > 10 && y <= 5
. - Logical Expressions: Combine relational expressions using logical operators like
&&
(and),||
(or),!
(not). Example:(x > 10 || y <= 5) && z === 0
. - Assignment Expressions: Assign values to variables. Example:
name = "John"; age = 30;
. - Function Call Expressions: Call functions to execute their code blocks and obtain return values. Example:
sum(5, 3)
, wheresum
is the function and5
and3
are the arguments. - Ternary Expressions: Ternary operators (
? :
) provide a concise way to define conditional values. Example:larger = (x > y) ? x : y;
.
Operators in Expressions:
- Arithmetic:
+
,-
,*
,/
,%
(remainder),**
(exponentiation). - Relational:
>
,<
,>=
,<=
,==
(equality),!=
(inequality). - Logical:
&&
(and),||
(or),!
(not). - Assignment:
=
,+=
,-=
,*=
,/=
. - Others:
typeof
,instanceof
,in
,delete
.
Operator Precedence:
The order of execution of operations in an expression is defined by precedence rules. Use parentheses to explicitly control the order.
Challenge:
- Create a JavaScript script that prompts the user for their name and age.
- Store the name and age in variables.
- Use operators to check if the user is of legal age.
- Display a personalized message in the console according to the user’s age.