Programming languages are defined by rules. The syntax is what we follow when we write our code, which forms the logical structure of our programs.
Let's dive right into the basic components of JavaScript. We will look at values, unicode, semi-colon, indentation, white spacing, commentary, case sensitivity, keywords..ect.
By taking the time to learn the basics, we will be well on our way to building more functional and readable code.
JavaScript: the Values
There are two types of values in JavaScript: Fixed values( or literals) and variables.
Literals
Literals are defined as values written in our code, such as numbers, strings, booleans, as well as literals for objects and arrays.
Examples:
18 // A number 'Toy' // A string (can be in double "" or single '' quotes) false // A boolean (can be true or false) ['a', 'b'] // An array {color: 'red', shape: 'Circle'} // An object
Variables
Variables are named values that store data. We declare our variables with the var, let or const keywords and assign values with the sign =.
For instance, the key is defined as a variable.
const key;
key = pluto;
Important:
Don’t use var. It should be used when you working with legacy code. It's the old pre-ES6 syntax.
Use let it if your variable needs to be updated within the program.
Use const it if your variable holds a constant value. It cannot be updated.
Camel Case
What if more than one word is our variable name? How do we declare a variable we need to name "first-item" for example?
We can't use hyphens such as "first-item" just because they are reserved for JavaScript subtractions.
Underscores such us first_name? We coul... but it has a tendency to make our code look messy and confusing.
What solution do we propose?
camel case! e.g. firstItem.
The first word is lower-case, the first letter of any subsequent words are upper-case.
Unicode
JavaScript uses a set of characters with unicode. Unicode covers almost all the characters, punctuations and symbols!. This is great because we can write our names in any language and even emojis can be used as variable names
Semicolons
JavaScript programs are built up with instructions known as statements. Such as:
let a = 500;
a = b + c;
const time = Date.now();
JavaScript statements often end in a semicolon ;. But semicolons aren’t always mandatory! JavaScript does not have any issues if you don’t use them.
// valid!
let a = 500
a = b + c
const time = Date.now()
But again, there are some situations in which they are obligatory. For example, when we use a for loop, such as:
for (i = 0; i < .length; i++) { }
When using a block statement however, semicolons are not to be included after the curly braces, for example:
if (name == "Silvia") { // code } // <- no ';'
//or,
function people(name) { // code } // <- no ';'
If we’re using an object however, like:
const person = { firstName: "Silvia", lastName: "Brown", age: 30, eyeColor: "green" }; // the ';' is mandatory
Indentation
Technically, we could write a whole program of JavaScript on one line. But itwould be almost impossible to read and maintain. That's why lines and indentation are used. The conditional statement can be used as an example:
if (loginSuccessful === 1) { // run code } else { // abort }
By applying indentation we’ll have a code cleaner, more maintainable and readable! Look:
if (loginAttempts < 5){ if (loginAttempts < 3){ alert("< 3"); } else { alert("between 3 and 5"); } } else { if (loginAttempts > 10){ alert("> 10"); } else { alert("between 5 and 10"); } }
White Space
JavaScript requires only one space between keywords, names, and identifiers, or any white space will be completely ignored. This means that there is no difference in the language between the following statements:
const visitedCities="Rome, "+"Florence, "+"Venice"; const visitedCities = "Rome, " + "Florence, " + "Venice";
Don't tou think the second one's more readable?
Another example:
let x=1*y; let x = 1 * y;
Again, the second line is much easier to read and debug!
Commenting
A comment is code which can not be executed. They are useful for illustrating some code in a program. And also to' comment' on a code section to prevent execution- often used to test an alternative piece of code. JavaScript has two types of comments:
// Comment goes here
/* Comment goes here */
When writing code you may have some complex logic that is confusing, this is a perfect opportunity to include some comments in the code that will explain what is going on. Not only will this help you remember it later on, but if you someone else views your code, they will also be able to understand the code (hopefully)!
Identifiers
JavaScript Identifiers are names given to variables, functions, etc.
While naming your variables in JavaScript, keep the following rules in mind.
- You should not use any of the JavaScript reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid.
- JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 5demo is an invalid variable name but _5demo is a valid one.
- JavaScript variable names are case-sensitive. For example, Name and name are two different variables.
Examples:
// Valid :)
Name name NAME _name Name1 $name
// Invalid :(
1name n@me name!
Case Sensitivity
JavaScript is a case-sensitive language. This means that language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters. The while keyword, for example, must be typed “while”, not “While” or “WHILE”. Similarly, online, Online, OnLine, and ONLINE are four distinct variable names.
The following will throw an error:
function test() { alert("This is a test!"); }
function show_alert() { Test(); // error! test(); is correct }
Reserved Words
What reserved words are there in JavaScript?
Reserved words of the JavaScript langauge are listed below. (Some of these words are actually used in the Java language, and are reserved in JavaScript for compatibility purposes or as possible extensions.) When choosing names for your JavaScript variables, avoid these reseved words!
break, do, instanceof, typeof, case, else, new, var, catch, finally, return, void, continue, for, switch, while, debugger, function, this, with, default, if, throw, delete, in, try, class, enum, extends, super, const, export, import.
See the full list of reserved keywords.
JavaScript Operators
Operators in JavaScript are very similar to operators that appear in other programming languages. The definition of an operator is a symbol that is used to perform an operation. Most often these operations are arithmetic (addition, subtraction, etc), but not always.
Arithmetical operators + - * and / are primarily used when performing calculations within JavaScript, such as
(2 + 2) * 100
The assignment operator = is used to assign values to our variables
JavaScript Expressions
Expressions are units of code that can be evaluated and resolve to a value. Expressions in JS can be divided in categories.;
- Arithmetic expressions
- String expressions
- Primary expressions
- Array and object initializers expressions
- Logical expressions
- Left-hand-side expressions
- Property access expressions
- Object creation expressions
- Function definition expressions
- Invocation expressions
ARITHMETIC EXPRESSIONS
Under this category go all expressions that evaluate to a number:
1 / 2 i++ i -= 2 i * 2
STRING EXPRESSIONS
Expressions that evaluate to a string:
'A ' + 'string' 'A ' += 'string'
PRIMARY EXPRESSIONS
Under this category go variable references, literals and constants:
2 0.02 'something' true false this //the current object undefined i //where i is a variable or a constant
but also some language keywords:
function class function* //the generator function yield //the generator pauser/resumer yield* //delegate to another generator or iterator async function* //async function expression await //async function pause/resume/wait for completion /pattern/i //regex () // grouping
ARRAY AND OBJECT INITIALIZERS EXPRESSIONS
[] //array literal {} //object literal [1,2,3] {a: 1, b: 2} {a: {b: 1}}
LOGICAL EXPRESSIONS
Logical expressions make use of logical operators and resolve to a boolean value:
a && b a || b !a
LEFT-HAND-SIDE EXPRESSIONS
new //create an instance of a constructor super //calls the parent constructor ...obj //expression using the spread operator
PROPERTY ACCESS EXPRESSIONS
object.property //reference a property (or method) of an object object[property] object['property']
OBJECT CREATION EXPRESSIONS
new object() new a(1) new MyRectangle('name', 2, {a: 4})
FUNCTION DEFINITION EXPRESSIONS
function() {} function(a, b) { return a * b } (a, b) => a * b a => a * 2 () => { return 2 }
INVOCATION EXPRESSIONS
The syntax for calling a function or method
a.x(2) window.resize()
Conclusion
This article was intended to provide an overview of JavaScript 's basic syntax and structure. We have looked at many of the common conventions, but remember that you can be somewhat flexible-especially when you work with your own specific standards in collaborative work environments.
Syntax and structuring play an important role both in the functionality of our programs and in the readability and maintenance of codes.
We hope you found this article useful!
Janeth Kent
Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN AND DEVELOPMENT.
Related Posts
How to upload files to the server using JavaScript
In this tutorial we are going to see how you can upload files to a server using Node.js using JavaScript, which is very common. For example, you might want to…
How to combine multiple objects in JavaScript
In JavaScript you can merge multiple objects in a variety of ways. The most commonly used methods are the spread operator ... and the Object.assign() function. How to copy objects with…
The Payment Request API: Revolutionizing Online Payments (Part 2)
In the first part of this series, we explored the fundamentals of the Payment Request API and how it simplifies the payment experience. Now, let's delve deeper into advanced features…
The Payment Request API: Revolutionizing Online Payments (Part 1)
The Payment Request API has emerged as the new standard for online payments, transforming the way transactions are conducted on the internet. In this two-part series, we will delve into…
Let's create a Color Picker from scratch with HTML5 Canvas, Javascript and CSS3
HTML5 Canvas is a technology that allows developers to generate real-time graphics and animations using JavaScript. It provides a blank canvas on which graphical elements, such as lines, shapes, images…
How do you stop JavaScript execution for a while: sleep()
A sleep()function is a function that allows you to stop the execution of code for a certain amount of time. Using a function similar to this can be interesting for…
Mastering array sorting in JavaScript: a guide to the sort() function
In this article, I will explain the usage and potential of the sort() function in JavaScript. What does the sort() function do? The sort() function allows you to sort the elements of…
Infinite scrolling with native JavaScript using the Fetch API
I have long wanted to talk about how infinite scroll functionality can be implemented in a list of items that might be on any Web page. Infinite scroll is a technique…
Sorting elements with SortableJS and storing them in localStorage
SortableJS is a JavaScript extension that you will be able to use in your developments to offer your users the possibility to drag and drop elements in order to change…
What is a JWT token and how does it work?
JWT tokens are a standard used to create application access tokens, enabling user authentication in web applications. Specifically, it follows the RFC 7519 standard. What is a JWT token A JWT token…
Template Literals in JavaScript
Template literals, also known as template literals, appeared in JavaScript in its ES6 version, providing a new method of declaring strings using inverted quotes, offering several new and improved possibilities. About…
How to use the endsWith method in JavaScript
In this short tutorial, we are going to see what the endsWith method, introduced in JavaScript ES6, is and how it is used with strings in JavaScript. The endsWith method is…