JavaScript's declaration

Source: Internet
Author: User

Why does the following JavaScript code work?

Hello ();
    
function Hello () {
    alert ("Hello, world!");
}

But for C, this would be an error:

#include "stdio.h"
    
void Main () {
    hello ();
}
    
void Hello () {
    printf ("Hello, worldn");
}

Since hello is not previously declared, the Code "Hello ()" is considered to be an implicit declaration, and the return type of the implicit declaration is int, so the hint Hello type error.

It is easy to solve this problem by either declaring it beforehand or putting the main function behind the Hello function.

So what does it mean for JavaScript to work?

The statement that was promoted

The JavaScript engine interprets the code first, the declaration is promoted, and then executes. For example, in order to determine whether a variable is defined or not, if we write this, the reference is incorrect:

if (Somevar = = undefined) {
    alert ("Somevar undefined");
}

But if this doesn't go wrong:

if (Somevar = = undefined) {
    var somevar = 1;
    Alert ("Somevar not Defined");
}

The visible declaration was elevated, but only the declaration was promoted, because Somevar remained equal to undefined, not 1.

It is worth mentioning that this kind of writing will also be an error:

if (Somevar = = undefined) {
    somevar = 1;
    Alert ("Somevar not Defined");
}

This proves that implicit declarations are of no effect at the interpretation stage! And to make the code logically clear, use explicit declarations!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.