Is javascript case sensitive. JavaScript - Syntax. Whitespace in JavaScript

💖 Do you like it? Share the link with your friends

A JavaScript program consists of variables, operators, functions, objects and other language constructs. All of them will be discussed in detail in this textbook. And in this topic I will tell you how they are written in the program code. JavaScript syntax is common and largely coincides with other programming languages.

Spaces and line feed

JavaScript does not require spaces between variables and various statements. But it allows you to put spaces where you need:

Line translation can also be done where it is convenient for you. There is one exception: you cannot create a line break inside text that is in quotation marks. This issue will be discussed in more detail when studying strings. In other cases, you decide for yourself where to translate the line

You can write it like this:

However, I recommend using a semicolon after every statement and function call. First, the absence of a semicolon is not always acceptable, and an error may occur. Secondly, this is a common style of competent coding, and it’s better to get used to it right away. It is advisable to follow the rule: each line must end with a semicolon. The exception is language constructions, which have their own signs. For example, some operators.

When writing your names, for example, when creating variables, character case is also taken into account. company and Company are two different variables.

JavaScript syntax is a set of rules for how JavaScript programs are built.

JavaScript Programs

A computer program is a list of "instructions" to be "executed" by the computer.

In a programming language, these program instructions are called statements.

JavaScript is a programming language.

JavaScript statements are separated by semicolons.

HTML, JavaScript programs can be executed using a web browser.

JavaScript Statements

JavaScript statements consist of:

Values, Operators, Expressions, keywords and comments.

JavaScript values

JavaScript syntax defines two types of values: Fixed values ​​and variable values.

Fixed values ​​are called literals. The values ​​of variables are called variables.

JavaScript literals

The most important rules for writing fixed values ​​are:

Numbers are written with or without decimal places:

Lines of text written in double or single quotes:

JavaScript Variables

In a programming language, variables are used to store data values.

JavaScript uses the var keyword to declare variables.

The equal sign is used to assign values ​​to variables.

In this example, x is defined as a variable. Then x is assigned (given) the value 6:

JavaScript Operators

JavaScript uses the assignment operator (=) to assign values ​​to variables:

JavaScript uses arithmetic operators(+ - * /) to calculate values:

JavaScript Expressions

An expression is a combination of values, variables, and operators that evaluates to a value.

The calculation is called estimation.

For example, 5 * 10 takes the value 50:

Expressions can also contain variable values:

Values ​​can be various types, such as numbers and strings.

For example, "John" + "," + "Doe" takes the value "John Doe":

JavaScript Keywords

JavaScript keywords are used to define the actions to be performed.

The var keyword tells the browser to create a new variable:

JavaScript Comments

Not all JavaScript statements will be "executed".

Code after double slashes // or between /* and */ is treated as a comment.

Comments are ignored and will not be executed:

JavaScript Identifiers

Identifiers are names.

In JavaScript, identifiers are used to name variables (and keywords, as well as functions and labels).

The rules for legal names are the same in most programming languages.

In JavaScript, the first character must be a letter, an underscore (_) or a dollar sign ($) .

Subsequent characters can be letters, numbers, underscores, or dollar signs.

Numbers are not allowed as the first character.
This way JavaScript can easily distinguish identifiers from numbers.

JavaScript is case sensitive

All JavaScript identifiers are case sensitive.

The variables LastName and LAST NAME are two different variables.

JavaScript does not interpret VAR or Var as the var keyword.

JavaScript and Camel Case

Historically, programmers have used three ways to combine multiple words into a single variable name:

Hyphens:

first-name, last-name, master-card, inter-city.

Hyphens are not allowed in JavaScript. It is intended for subtractions.

Underscore:

first_name, last_name, master_card, inter_city.

Camel case:

FirstName, LastName, MasterCard, InterCity.

In programming languages, especially JavaScript, the camel case often begins with a lowercase letter:

firstName, lastName, masterCard, interCity.

JavaScript Character Set

JavaScript uses the Unicode character set.

Unicode covers (almost) every character, punctuation and glyph in the world.

JavaScript is a language and it has its own syntax, which it would be nice to know well.
A JavaScript program consists of sentences that are separated by semicolons.

Sometimes you can miss a semicolon and get away with it, but not always. Therefore, in cases where the end of a sentence is implied, it is better not to forget to put it.

If you inadvertently omit semicolons, spaces, or for some other reason your code does not have a style (and this is important!), then I recommend ESLint.

Offers consist of:

  • Values
  • Operators
  • Expressions
  • Keywords
  • Comments

There are two types of values ​​in JavaScript: variables and literals.

Variables

Variables are used to store values. JavaScript uses the var keyword to declare variables.
We can declare variables in three ways:

  • Using the var keyword. For example, var y = 56;
  • Simply by assigning a value. For example, y = 56;
    But this option is undesirable, since in this case the variable becomes global.
    Why is a global variable bad? If only because, becoming global, it goes out of control of the scope of the function. It can either be changed by other code, or it can itself rewrite the value in someone else’s code
  • Using the let keyword.
    Because In JavaScript (before ECMAScript 6) there is no scope within a block, let was introduced, which allows you to declare variables with a scope - a block.
    For example, if (true) (let y = 4;) console.log(y); // ReferenceError: y is not defined

    You can view current ES6 support.

Literals

Literals are fixed values. These include data types such as null, Boolean, Number, Object, String.
For example, when we declare an array, the part that comes after the equal sign is an array literal.

Var food = ['cheese','potates','cucumber'];

And food is a variable.

Numbers

Numbers are written with or without decimal places.

10.50 1001

In order for the interpreter to understand what the dot means - a method call or a floating point, we need to prompt it in one of the following ways:

1..toString() 1 .toString() // space before dot (1).toString() 1.0.toString()

String

String - text written using double or single quotes.

"I am string“ "And I am string“

Basically, you need to decide which quotes to use and follow your choice as you write your code.

By default, ESLint settings even provide a choice based on the results of which the code will be checked.

Identifiers

The name we give to variables, functions, and properties is called an identifier.
It can only contain alphanumeric characters, "$" and "_".
How is an identifier different from a String?

String is data, and the identifier is part of the code.

Var surname = “Smit”;

“Smit” is uniquely the data - a string literal, while surname is the store for that value.
Note that a hyphen is not allowed in the identifier because it is used for subtraction.

Expressions

An expression is a combination of values, variables, operators that calculates a value.
For example, the expression 3 * 5 evaluates to 15.
The expression can also contain a variable
x*4
Of course, the values ​​can also be strings.
For example the expression:

"The day" + " is " + "sunny" //calculated into the string "The day is sunny".

Expressions can be divided into those that assign a value to a variable and those that simply calculate values.
First case:

and second:

By the way, as soon as we add a semicolon, we no longer have an expression, but a sentence!

Var x = 56;

Comma for expressions

Comma evaluates both operands and returns the right value.

Var x = 0; var y = (x++, 4); console.log(x); //1 console.log(y); //4

Expressions evaluate to a value and can be written anywhere a value is expected. For example, an argument in a function call or the right side of an assignment.

Each of following lines contains the expression:

X x + 6 changeArray("a","b")

Wherever js expects a sentence, you can also write expressions.
Such a sentence is called an instruction-expression.

But you can't write a sentence where js assumes an expression. For example, an IF clause cannot become a function argument.

Comparison of sentence and expression

Let's look at the IF clause and the conditional statement, which is an expression.

Var result; if (x > 0) ( result = " Positive number"; ) else ( result = "Negative number"; )

Equivalent:

Var result = (x > 0 ? "Positive number" : "Negative number");

Between the sign = and ; expression.
To prevent ambiguity in parsing, JS does not allow object literals and function expressions to be used as clauses.

It follows from this that expression sentences should not begin with:

  • curly braces
  • with the function keyword

If an expression begins with one or the other, then it should be written in the context of the expression.
To do this, the expression is placed in parentheses.

Function declaration and function expression

Let's say we want to declare an anonymous function-expression, then we write like this:

(function())(return "ready!")());

Let's look at how this function will differ from a function declaration like

Function getReady() ( return "ready!" )

  • Obviously, the anonymous one has no name. But it may well be, then it will be a named function expression.
  • A function declaration is created by the interpreter before the code is executed, while a function expression is created only during execution.
  • Therefore, expression functions are not available until they are declared.

What if we write it like this?

GetReady(); var getReady = function())( return "ready!"; ) getReady();

In the first line we get an error: TypeError: getReady is not a function
The fifth will display “ready” to us, since the function has already been declared.
This phenomenon is called hoisting, why it occurs is described in the post about.

When learning to write, a person must learn the basics of spelling, grammar and spelling. For example, everyone knows that a sentence begins with a capital letter and ends with a period, the text is divided into paragraphs, etc.

Programming languages ​​work in a similar way: in order for a program to work, certain rules must be followed. The set of rules that define the structure of programming languages ​​is called syntax. Many programming languages ​​are built on the same concepts but use different syntax.

This tutorial will introduce you to the basics of syntax and code structuring in JavaScript.

Functionality and readability

Functionality and readability are very important aspects of JavaScript syntax that need to be focused on separately.

Some syntax rules are mandatory for JavaScript code. If they are not met, the console will throw an error and the script will stop running.

Consider this error in the “Hello, World!” program.

// Example of a broken JavaScript program
console.log("Hello, World!"

There is a missing closing bracket at the end, so instead of the line “Hello, World!” the program will return an error:

Uncaught SyntaxError: missing) after argument list

To allow the script to continue running, you must add a closing parenthesis. This is the error in JavaScript syntax may affect the operation of the program.

Some aspects of JavaScript syntax and formatting come from different perspectives. Simply put, there are stylistic rules and variations that are optional and do not cause errors when running the code. However, there are also many general conventions that are wise to keep track of so that project and code developers are aware of style and syntax updates. Following common conventions will improve the readability of your code.

Consider the following three options for assigning a value to a variable:

const greeting="Hello"; // no whitespace between variable & string
const greeting = "Hello"; //excessive whitespace after assignment
const greeting = "Hello"; // single whitespace between variable & string

All three lines above will work the same. But the third option (greeting = "Hello") is by far the most commonly used and readable way to write code, especially when viewed in the context of a larger program.

It is very important to monitor the integrity and consistency of all program code.

Below we'll look at a few examples to familiarize ourselves with the syntax and structure of JavaScript code.

Whitespace characters

JavaScript whitespace characters are spaces, tabs, and line feeds (this action is performed by the Enter key). As shown earlier, excess white space outside of a line, white space between operators, and other characters are ignored by the JavaScript interpreter. This means that the following three variable assignment examples will have the same result:

const userLocation = "New York City, " + "NY";
const userLocation="New York City, "+"NY";
const userLocation = "New York City, " + "NY";

The userLocation variable will have the value "New York City, NY" regardless of the assignment style for that value. For JavaScript, it doesn't matter what whitespace characters are used.

There is one tried and true rule in writing programs: when you use whitespace, follow the same rules that you use in math or grammar. For example, the line:

easier to read than:

An important exception to this rule is the assignment of multiple variables. Notice the = position in the following example:

const companyName = "MyCompany";
const companyHeadquarters = "New York City";
const companyHandle = "mycompany";

All assignment operators (=) are aligned on a single line using spaces. This type of structure is not used by all code bases, but can improve readability.

Extra line breaks are also ignored in JavaScript. As a rule, additional empty lines are inserted above the comment and after the code block.

Round brackets

Keywords such as if, switch, and for usually have spaces before and after parentheses. Consider the following example:

// An example of if statement syntax
if () ( )
// Check math equation and print a string to the console
if(4< 5) {
console.log("4 is less than 5.");
}
// An example of for loop syntax
for () ( )
// Iterate 10 times, printing out each iteration number to the console
for (let i = 0; i 0) (
square(number);
}

Be careful, as not all code contained in braces, does not require a semicolon. Objects are enclosed in curly braces and must end with a semicolon.

// An example object
const objectName = ();
// Initialize triangle object
const triangle = (
type: "right",
angle: 90,
sides: 3,
};

It is a common practice to place semicolons after each statement and JavaScript expressions, except those ending in curly braces.

Code Structuring

Technically, all of the code in a JavaScript program can be put on one line. But such code is very difficult to read and maintain. Therefore the program is divided into lines.

For example, the if/else statement can be written in one line, or it can be divided:

// Conditional statement written on one line
if (x === 1) ( /* execute code if true */ ) else ( /* execute code if false */ )
// Conditional statement with indentation
if (x === 1) (
// execute code if true
) else (
// execute code if false
}

Please note: any code included in a block is indented. You can indent using two spaces, four spaces or tabs. The choice of indentation method depends solely on personal preference or the recommendations of your organization.

An open parenthesis at the end of the first line is a common way to structure JavaScript statements and objects. Sometimes the brackets are placed on separate lines:

// Conditional statement with braces on newlines
if (x === 1)
{
// execute code if true
}
else
{
// execute code if false
}

This structure is rarely used in JavaScript, as in other languages.

Nested statements must be separated:

// Initialize a function
function isEqualToOne(x) (
// Check if x is equal to one
if (x === 1) (
// on success, return true
return true;
) else (
return false;
}
}

Proper indentation makes the code readable. The only exception to this rule to keep in mind is that compressed libraries remove all unnecessary symbols to reduce file size.

Identifiers

The names of variables, functions or properties in JavaScript are called identifiers. Identifiers consist of letters and numbers, but they cannot contain characters beyond $ and _ and cannot begin with a number.

Case sensitivity

Names are case sensitive. That is, myVariable and myvariable will be treated as two different variables.

var myVariable = 1;
var myvariable = 2;

By general convention, names are written in camel case: the first word is written with a lowercase letter, but each subsequent word begins with a capital letter. Global variables or constants are written in uppercase and are separated by underscores.

const INSURANCE_RATE = 0.4;

The exception to this rule is class names, where each word typically begins with a capital letter (PascalCase).

// Initialize a class
class ExampleClass (
constructor()
}

To ensure code readability, you must use identifiers consistently across all program files.

Reserved Keywords

Identifiers must also not contain any reserved keywords. Keywords are JavaScript words that have built-in functionality. These include var, if, for and this.

For example, you cannot assign a value to a variable named var.

var var = "Some value";

JavaScript knows the var keyword, so it will throw an error:

SyntaxError: Unexpected token (1:4)

JavaScript can be implemented using JavaScript operators, which are placed in HTML tags script ... /script on a web page.

You can place script tags containing your JavaScript anywhere on your web page, but it's generally recommended to store it in head tags.

The script tag alerts the browser program to begin interpreting all text between these tags as script. The simple syntax for your JavaScript would look like this.

JavaScript code

The script tag contains two important attributes -

  • Language - This attribute indicates what scripting language you are using. Typically its value will be javascript. Although recent HTML versions(and XHTML, its successor) have stopped using this attribute.
  • Type. This attribute is now recommended to indicate the scripting language used and its value should be set to "text/javascript".

So your JavaScript segment would look like this:

JavaScript code

Your first JavaScript script

Let's take the example of the "Hello World" printout. We've added an extra HTML comment that surrounds our JavaScript code. This is to save our code from a browser that doesn't support JavaScript. The comment ends with "// ->". Here "//" means a comment in JavaScript, so we add this to prevent the browser from reading the end HTML comments as part of JavaScript code. We then call the document.write function, which writes a string to our HTML document.

This function can be used to write text, HTML, or both. Take a look at the following code.

This code will give the following result:

Hello World!

Spaces and line breaks

JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. You can freely use spaces, tabs, and newlines in your program, and you can format and indent your programs in a neat and consistent manner, making your code easy to read and understand.

Semicolons in JavaScript

IN simple instructions in JavaScript it is usually followed by a semicolon, as in C, C++ and Java. JavaScript, however, allows you to skip this semicolon if you put each of your statements on a separate line. For example, the following code could be written without semicolons.

But when formatting in one line like this, you have to use semicolons -

Note. It is good programming practice to use semicolons.

Case sensitivity

JavaScript is a case-sensitive language. This means that keywords, variables, function names, and any other identifiers must always be entered with a consistent capital letter.

So the Time and TIME identifiers will convey different meanings to JavaScript.

NOTE. You should be careful when writing variable and function names in JavaScript.



tell friends