Home > Article > Web Front-end > Day f 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!
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:
// This is a single-line comment console.log("Hello World"); // This is another single-line comment
/* This is a multi-line comment. It can span multiple lines. */ console.log("Hello World");
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:
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
If declared outside a function, var is accessible throughout the program.
var name = "Alice"; console.log(name); // Accessible globally
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
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
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"
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!
The above is the detailed content of Day f JavaScript. For more information, please follow other related articles on the PHP Chinese website!