DEV Community

Shoyab khan
Shoyab khan

Posted on

Day 3 of 30: JavaScript

Hey curious readers! I'm back with the third tutorial on JavaScript. In this post, we will explore how comments are used and how variables are declared in JavaScript. Let's get started!

1. Comments in JavaScript

What are comments?
Comments are pieces of text in the code that help explain what the code does. They are not executed as part of the program and are meant to enhance code readability.

Types of comments:

  • Single-line comments: These are represented by double slashes //.
// This is a single-line comment
console.log("Hello World"); // This is another single-line comment
Enter fullscreen mode Exit fullscreen mode
  • Multi-line comments: These are used for longer comments that span multiple lines. They are enclosed by /* at the beginning and */ at the end.
/* 
  This is a multi-line comment.
  It can span multiple lines.
*/
console.log("Hello World");
Enter fullscreen mode Exit fullscreen mode

2. Variable Declaration

What are variables?
Variables are symbolic names for values and are used to store data that can be referenced and manipulated in a program.

Ways to declare variables in JavaScript:

  • Using var keyword
  • Using let keyword
  • Using const keyword

Using var keyword:
var is the traditional way to declare variables in JavaScript. Variables declared with var are function-scoped or globally scoped.

function exampleFunction() {
  var name = "Alice";
  console.log(name); // Accessible inside the function
}
exampleFunction();
console.log(name); // Error: name is not defined
Enter fullscreen mode Exit fullscreen mode

If declared outside a function, var is accessible throughout the program.

var name = "Alice";
console.log(name); // Accessible globally
Enter fullscreen mode Exit fullscreen mode

Using let keyword:
Introduced in ECMAScript 2015 (ES6), let allows you to declare block-scoped variables.

{
  let name = "Bob";
  console.log(name); // Accessible within this block
}
console.log(name); // Error: name is not defined
Enter fullscreen mode Exit fullscreen mode

let cannot be redeclared within the same scope.

Using const keyword:
Also introduced in ECMAScript 2015 (ES6), const allows you to declare constants, which are block-scoped like let. The value of a constant cannot be reassigned once it is initialized.

const name = "Charlie";
console.log(name); // "Charlie"
name = "Dave"; // Error: Assignment to constant variable
Enter fullscreen mode Exit fullscreen mode

However, properties of objects or elements of arrays declared with const can still be changed.

const person = { name: "Eve" };
person.name = "Frank"; // Allowed
console.log(person.name); // "Frank"
Enter fullscreen mode Exit fullscreen mode

That's it for this post. I hope you now understand how to use comments and declare variables in JavaScript. In the next post, we will explore data types. Stay connected and don't forget to follow me!

Top comments (0)