Declaration vs Expression: What every programmer should know

In the exciting world of JavaScript programming, two fundamental concepts govern the creation of variables, functions, and logical structures: declarations and expressions. Understanding the difference between these two cornerstones is essential to writing precise and efficient code.

by
Andrés Jimenez
|
February 29, 2024

A statement is an instruction that tells the language what to do. It can declare a variable, function, class, etc. Declarations are used to establish the structure and rules of the program.

Understanding the differences between declaration and expression is essential to writing precise and efficient code. By using declarations, we can establish the structure and rules of the program in an organized manner.

On the other hand, by using expressions, we can perform calculations and manipulate data efficiently. When writing code, it is essential to consider what type of instruction is needed in each situation.

For example, if we want to assign a value to a variable, we must use an assignment expression. If we're going to define a function, we must use a function declaration. Additionally, understanding the differences between statements and terms helps us avoid common mistakes.

For example, we are treating a statement as an expression or vice versa, as this can cause problems in the program logic and make debugging difficult.

In this article,we will explore when to use expressions and statements. We will also explain the differences between them. Go for it!

Declaration and its function in JavaScript

Declarations in JavaScript

Declarations in JavaScript are the foundation on which your code is built. It is an instruction that tells language what to do. In JavaScript, declarations are used to establish the structure and rules of the program. Here are some examples of common statements:

  • Declaration of variables: In JavaScript, we can declare variables using the keywords `var', `let', or `const'. For example:

var name = "Sebastian";

let age = 22;

const PI = 3.1416;

In this case, we are declaring the variables`name`, `age`, and `PI ' and assigning them specific values. Variables allow us to store and manipulate data in our program.

  • Function declaration: In JavaScript, we can declare functions using the keyword `function`. For example:

function greet() {

  console.log("Hello welcome!");

}

greet(); // Function call

In this case, we are declaring a function called 'greet' which displays a message on the console. Then, we can call the function using its name followed by parentheses.

  • Class declaration: In JavaScript, we can declare classes using the keyword `class`. For example:

class Person {

  constructor(name Age) {

    this.name = name;

    this.age = age;

  }

  greet() {

    console.log(`Hello, my name is ${this.name} and I have ${this.age} years.`);

  }

}

const persona1 = new Person("Sebastian", 22);

person1.greet();// Call to the class method

In this case, we are declaring a class called `Person ' with a constructor and a method 'greet.' Next, we create an instance of the class and call the method using the instance.

Importance of declarations for the structure and organization of the code

Declarations play a fundamental role in the structure and organization of code in JavaScript.Here are several reasons why declarations are important to the structure and organization of your code:

  • Modularity and Code Reuse: Function declarations allow you to define code fragments that perform specific tasks. By giving a function a name, you can reuse that logic in multiple places in your program without having to rewrite it. This encourages modularity, making your code easier to understand and maintain.
  • Structure and Readability: Organizing code into functions makes it easier to divide your program into smaller, more manageable sections. Each function has a specific purpose, which improves readability.
  • Hierarchical Organization: Function declarations allow you to organize your code in a hierarchical structure. You can have functions that call other functions, creating a hierarchy of tasks. This makes it easier to understand how your program behaves in different situations.
  • Facilitates Maintenance: When you need to make changes or fixes to your code, it's much easier if your program is well-organized with function declarations. You can focus on the affected function, without worrying about how it impacts other parts of the code.
  • Facilitates Debugging: When errors occur in your program, function declarations help you more quickly identify the cause of the problem. You can isolate and test each function separately to find where the error occurs.

Expression and its role in JavaScript

Expression in JavaScript

Unlike the statements, expressions in JavaScript do produce or evaluate to a specific value. The expressions can be literals (such as strings or numbers), variables, operators, function calls, or any other unit of code that returns a value.

They are essential for performing a variety of tasks, from mathematical calculations to evaluating conditions and assigning values. Here's how the expressions are used in different contexts:

  • Mathematical calculations: Expressions are used to perform arithmetic calculations. For example, you can add, subtract, multiply, and divide numbers using arithmetic operators, such as `+`, `-`, `*`, and `/`. Here is an example:

   const sum =5 + 2; // Make a sum

   const subtraction = 10 - 3; // Perform a subtraction

   const product = 6 * 4; // Perform a multiplication

   const division = 8 / 6; // Perform a division

   

  • Condition Evaluation: Expressions are used to evaluate conditions and make decisions in code. For it,comparison operators are used, such as `==`, `===`, `!=`, `<`, `>`, `<=` and `>=`, along with logical operators, such as `&&` (AND) y `||` (OR). Here are examples:

   const age = 25;

   const adult = age >=18; // Check if the person is of legal age

   const isStudent = true;

   const hasJob =false;

   const isYoung = isStudent && !hasJob; // Check if someone is young and doesn't have a job

  • Value Assignment: The expressions assign a value to a variable. You can use the assignment operator (=) to assign a value to a variable. For example:

let name = "feel"; // Assigns the value "Santi" to the variable name

Another example could be:

let number = 42; // Assigns the value 42 to the variable 'number'

  • Function calls:Expressions are used to call functions and get a return value. This allows you to perform calculations, execute logic in a function, and then use the result. For example:

  

function sum(a, b) {

  return a + b;

}

const result = addition(5, 7); // Call the 'sum' function and store the result in 'result'

  • Conditional expressions:Expressions are used to evaluate conditions and return different values ​​based on the result. Conditional operators are used, such as the ternary operator(? :). For example:

  

   was age =18;

   was isOfAge = (age >=18) ? "Yeah" : "No"; // isMayorDeAge is "Yes"

  • Function Expressions: You can assign functions to variables or object properties as an expression. This is useful when you want to use functions as arguments or return functions from other functions. Here is an example:

const greet =function(name) {

  return `Hello, ${name}!`;

};

const message =greet("Sebastian"); // Call the 'greet' function and store the result in 'message'

Importance of expressions to perform operations and make decisions in the code

Their importance lies in the fact that they allow calculations to be carried out, conditions to be evaluated, and values ​​to be assigned dynamically in the code, which is essential for developing interactive and functional applications.

  • It allows dynamic calculations and evaluation of values ​​in real-time.
  • They can be combined expressions to create complex formulas.
  • They provide much more flexibility by being able to use them as values.
  • Allow anonymous functions using arrow functions.
  • Different outcomes can be conditionally evaluated.
  • They allow values ​​to be assigned to variables and object properties.

In what expressions and declarations differ in Javascript

In JavaScript, there are fundamental differences between statements and expressions. Some of the key differences are highlighted below:

Result:

  •  The declarations: They do not produce a value directly. They are actions or instructions that are executed in the code.
  •  The expressions: On the other hand, they always produce a value. They can be as simple as a mathematical operation or as complex as a function.

Hoisting:

  •  The declarations of variables and functions are hoisted to the beginning of the scope in which they are defined. This means that you can use a variable or function declared before its declaration in the code.
  •  The expressions: They are not hoisted in the same way. You cannot use an expression before your statement In the code. This can cause errors if you try to use a function expression before defining it.

Common uses:

  • Declaring functions: They are used to define named functions that can be called anywhere in the code.
  •  Function expressions, especially anonymous ones, are helpful for quick, ad-hoc operations, such as returning functions in higher-order functions or creating functions in place (in place) in method calls.

Visibility:

  • Variable declarations and declared functions can have a global scope if they are defined in the global scope of the script.
  • The expressions are generally used to limit the scope of variables and functions since they can be declared and used locally.

Statements and expressions are used in different contexts in JavaScript programming.

Statements: Declarations are used to create variables, functions and control structures. Some contexts in which declarations are used are:

  • Declaration of variables: The keyword is used let, const or var followed by the variable name and optionally assigned an initial value.
  • Function declaration: The keyword is used as a function followed by the name of the function and its implementation.
  • Control structures: Statements like if, for, while, switch, among others, to control the flow of program execution.

Expressions: Expressions are used to perform calculations, evaluate conditions, and assign values. Some contexts in which expressions are used are:

  • Calculations and evaluation of conditions: Expressions are used to perform mathematical calculations and evaluate logical conditions. They are used in contexts where a calculated or estimated value is needed.
  • Return expressions: They are used to return a value from a function. They may contain additional logic to calculate the return value.
  • Value assignment: Expressions are used to assign values ​​to variables or properties of objects.
  • Callback expressions: They are used as arguments to higher-order functions, such as map, filter, and reduce, to specify the logic to apply to the elements of an array.
  • Function calls:Expressions are used to invoke functions and obtain their result.

Conclusion

In conclusion, declarations and expressions are two fundamental concepts in the world of JavaScript that play different but equally important roles.

Declarations establish the structure and organization of the code, allowing the creation of functions and variables that can be reused, improving readability and facilitating maintenance.

On the other hand, expressions are the driving force behind calculations, condition evaluations, and dynamic value assignment in code, which is essential for developing interactive and functional applications.

It is essential to understand the differences between statements and expressions, as well as their respective uses and advantages.

By mastering these concepts, programmers can write more precise, more efficient, and flexible code, allowing them to tackle a wide variety of programming tasks more effectively.

The choice of when to use statements or expressions depends on the situation and the specific requirements of the code.

Ultimately, this understanding is essential for any developer who wants to succeed in the exciting world of JavaScript programming.