Doubt about functions in Javascript lines

Asked

Viewed 31 times

4

I have a question about how functions work in Javascript, was looking at some examples and does not follow logic like other programming languages (PHP and Lua). I can create a Function on line 99 and call it on line 1 which will apparently work.

Take an example:

var exemplo = document.getElementByID('exemplo'),
    exemploDois = document.getElementByID('exemplo2');

    init();

    function init(){
        // ... function
    }

This in other languages would generate an error by returning a nil value. In Javascript do you not need to follow the function before calling it? This makes me a little confused when creating new JS codes.

In other languages the correct and the following:

var exemplo = document.getElementByID('exemplo'),
    exemploDois = document.getElementByID('exemplo2');

    function init(){
        // ... function
    }

    init();

Can the same be done in variables? So you understand the javascript does not need to follow guiding the functions before in the code.

  • 1

    is correct in both ways. Javascript is very quiet.

  • Declared functions with the function [name] go to the top of the command block if they are declared without the [name] they don’t go to the top of the block, so you can’t call the init before declaring it. Ex: init(); var init = function() {...};, then init will be undefined and an error is will be played on the console.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.