1.

Is JavaScript an interpreted language or compiled language?

Answer»

Let’s first understand what is an compiled language and interpreted language.

  • Compiled LANGUAGES are languages in which we turn a program first from human-readable format to machine format, generally through a compiler. After that we execute that code. So, it is generally a two-step process. Languages like C, C++ and Java are example of Compiled languages. For example if we have a “C” program(hello.c), we will first convert it into machine code by using a gcc(gnu C compiler) like below:
gcc hello.c -o hello

If no ERROR it will generate an executable “hello” and we will run it by:

./hello
  • Interpreted Languages are languages in which code doesn’t needs to be compiled first. Language like Perl, Python are interpreted languages. To run a python code we just need to run it directly by command like below:
python hello.py

The above code does not need to be compiled first but it does require that python is installed on any machine that needs to run the script.

  • JavaScript is a special case where you directly execute your source code. A webpage will directly execute your JavaScript. So, for that reason many people think JavaScript as a interpreted language.

However there is a compilation step just before the interpretation step in JavaScript. So, JS is both compiled and interpreted language.

  • Compilation Step – During this step the compiler MAINLY registers the variable declarations.

Let consider the below example. The compilation steps mainly looks at the var keyword. It is not BOTHERED with what is assigned in these variables.

var a = 10; var b = 20; console.log(a+b)

When the compiler goes to line 1, it encounters var a and registers it in the global scope and then goes to line 3 and registers the var b. Line 5 is only a console and it doesn’t finds any var, so don’t do anything.

  • Interpretation Step – During this the actual execution takes place. 

For the above example, the interpreter starts at line 1 and see a variable a and ask the compiler, if it have a variable “a” in Global scope and the compiler have it. So, it assigns the value 10 to it. Next the same step is repeated for line 3 and interpreter assigns 20 to variable “b”. 

Now once the interpreter goes to line 5, it finds console. It first looks for console at global scope from the compiler but don’t find it. So, it checks in the JavaScript global and finds it. Inside the console there are variable a and b, which it finds at global scope. It then adds them using addition operator and display the result.



Discussion

No Comment Found