javascript Tutorial

JavaScript Basics

Learn more about one of the world’s most popular programming languages.

JavaScript is the most popular programming language for adding interactive elements to websites. Although JavaScript is a powerful scripting language that can be used to create complex animations and graphics, database-driven applications, mobile apps, and video games, JavaScript basics are easy enough to grasp that beginners can learn JavaScript skills and, along with HTML and CSS, begin applying them to add functionality and interactivity to web pages right away.


JavaScript Fundamentals

Before getting started with JavaScript programming, it’s worth exploring JavaScript fundamentals and core JavaScript concepts, beginning with basic JavaScript language.

JavaScript was initially called Livescript because it was designed to make websites live or bring interactivity to it. JavaScript code is written as scripts. Hence, coding in JavaScript is called scripting. Using JavaScript is fairly straightforward as it does not require any setup. One can just open up a browser window and start writing JavaScript code.

Before we deep dive into JavaScript code, let’s help aspiring Web Developers understand some basic JavaScript terms:

JavaScript Variables

Variables are containers that store values, and in the JavaScript language, variables are crucial to creating anything interactive or dynamic because variables are needed to change values. You declare a variable with the var or the let keyword, and then you give the variable a value.

Variables can hold values with the following different data types:

  • String
  • Number
  • Boolean
  • Array
  • Objects and symbols

JavaScript Comments

JavaScript comments are brief bits of text that can be added alongside code that a web browser will ignore. You can add comments in JavaScript the same way you can in CSS. The comments can be used to prevent execution while you are testing alternative code, they can be used to explain JavaScript code, or they can be used to make code more readable.

JavaScript Operators

Operators are math symbols like addition, multiplication, division, and subtraction that produce results based on two values/variables. Basic JavaScript arithmetic operators are used to perform math operations on numbers, whereas JavaScript assignment operators give values to JavaScript variables, JavaScript comparison operators determine equality or difference between variables or values, and JavaScript string operators can be used to concatenate strings.

JavaScript Conditionals

Conditional statements in JavaScript are code structures used to perform different actions for different conditions. Conditionals are often used to test if an expression returns true or not. The most commonly found example would be the if … else statement. The if … statement scans a condition in parentheses and, if the result is true, a block of code is executed.

JavaScript Functions

JavaScript functions are blocks of code that you want to reuse so that you don’t have to write the same code over and over again. You can define a body of code as a function that can be executed whenever it’s invoked or called.

If you see what looks like a variable name followed by parentheses, it is probably a function. The parentheses contain arguments, which should be separated by commas if there are multiples.

JavaScript Events

To implement interactive elements on a website, you need event handlers, which run code in response to activity in the browser. When JavaScript code is used in HTML pages, JavaScript reacts to those events. Examples of events on an HTML page in JavaScript include a button click, information being entered into an input field, or a web page finishing the loading process.

HTML events include actions both by the user and the browser.

JavaScript Expressions

The smallest possible structure while writing code is called an Expression. An expression is anything that is a value or maybe the outcome in a piece of code. 2 + 3 is an expression because it produces a value that is 5.

JavaScript Statements

A statement is basically interchangeable with an expression. However, a statement is more of an instruction or one line of code that instructs the browser in this case to perform a task or carry out an operation. result = 2 + 3 is a statement because it does not necessarily produce a value but it does instruct the browser to store the value 5 in a variable called result.

JavaScript Syntax

Syntax of a programming language like JavaScript means the form or set of rules that a given statement or expression should follow. Programming languages are nothing but a sequence of characters and symbols and each language has its own way of defining what sequence is valid or invalid. When a piece of code in JavaScript does not adhere to its syntax, it is said to have syntax errors.

JavaScript Semantics

Semantics in contrast to syntax is the actual meaning of the programming language construct like an expression or a statement. It describes how the script or the program might be executed. It could also describe the browser or the platform on which the code is running and the input/output parameters needed to successfully execute the program. A piece of code with invalid syntax cannot be evaluated semantically because it is of an invalid structure not acceptable by the language.


JavaScript Best Practices

JavaScript best practices ensure quality code, improve code readability, and make it easier to maintain code. JavaScript best practices around file naming conventions and coding conventions include rules about naming and declaring variables and functions, using whitespace, indentation, and comments, as well as general JavaScript programming practices and principles. These best practices are standard to almost every JavaScript course and will often be documented for a web development, game development, or software development team to ensure strict adherence.

JavaScript best practices include:

JavaScript Coding Conventions

JavaScript code conventions include always using two spaces to indent code blocks (never tabulators, which are interpreted differently by different editors), putting space around operators and after commas, always ending a statement with a semicolon, and avoiding lines longer than 80 characters.

Although browsers tend to be forgiving around JavaScript syntax — which is part of why JavaScript is considered such a beginner-friendly programming language — that does not mean you should make a habit out of writing messy code.

Clean code means fewer bugs to troubleshoot, better code security, and an easier time involving other Programmers. Clean code can also be converted by scripts to other formats, rather than requiring human intervention.

JavaScript validation tools called linters can help you spot syntax issues in your code automatically when you save it.

Global variables and local variables

You should aim to minimize the use of global variables or avoid them entirely, including all objects, data types, and functions. Since every JavaScript file on a page runs in the same scope, having global functions or variables in your code could lead to a situation where other scripts included after yours could contain the same variable and function names and, as a result, overwrite your variables and functions. Using local variables instead is preferable.

Every variable used in a function should be declared as a local variable (they should be declared either with the var or let keyword or they will become global variables).

JavaScript Declarations

Best practice for JavaScript declarations is to put them at the top of each script or function. That makes it much easier to avoid unwanted global variables, minimize the chances of unintended re-declarations, and ultimately create cleaner code overall.

Treat JavaScript numbers, strings, or booleans as primitive values

You should avoid declaring string, number, and boolean as objects because it can greatly slow execution speed and lead to a host of unwanted side issues.

Block scored declarations

Since the beginning, JavaScript Developers have used var to declare variable, which can cause issues with the scope of the variables that are created when it’s used. Since the release of ES6, the const and let keywords empower Developers to declare variables in the block level scope, so the variables exist only within the corresponding block.


JavaScript File Naming Conventions

JavaScript file naming conventions ensure consistency and functionality for all JavaScript code that you write.

Some naming conventions come down to the choice of each Developer — for instance, many choose to write global variables and constants in uppercase — while there are some hard rules, like not beginning names with a $ sign (because it will conflict with the names of many JavaScript libraries).

There is debate among Programmers about using hyphens, underscores, or camelCase in variable names. JavaScript itself uses camelCase, as does as jQuery and other JavaScript libraries, so that’s generally recommended.

Other JavaScript file naming conventions to keep in mind include:

Be specific with names

The more specific you are, the less time you’ll have to waste trying to remember what the names are referring to. This also saves you from having to overpopulate your code with comments, which is another important best practice for JavaScript.

One-letter names

Again, to avoid slowing things down with unnecessary confusion, try to avoid using one-letter names. (An exception could be made for extremely common names.)

Although short names are generally better than long ones, it might be worth opting for a longer name in certain situations where the extra description will greatly help clarity.

Variable names

When you name a variable, the name should be clear and detailed enough that it leaves no doubt about what it is used for. Again, you shouldn’t need to write comments just to define variables.

Function names

Begin function names with a verb, since they’re used to perform actions. Try to be consistent with the same verbs for the same actions — this is not an area where you want to get creative with your verb choices.

Class and file names

Class names should be a noun and they should follow PascalCase. For JavaScript file names, either PascalCase or kebab-case are usually used and it comes down to personal choice. PascalCase should be used for component names with React.

Learn JavaScript Today

Get hands-on experience writing code with interactive tutorials in our free online learning platform.

  • Free and fun
  • Designed for beginners
  • No downloads or setup required