JavaScript
Article

5 Typical JavaScript Interview Exercises

By Aurelio De Rosa

JavaScript developers are in high demand in the IT world. If this is the role that best expresses your knowledge, you have a lot of opportunities to change the company you work for and increase your salary. But before you are hired by a company, you have to demonstrate your skills in order to pass the interview process. In this article I’ll show you 5 typical questions asked for a front end job to test the JavaScript skills of the candidate and their relative solutions. It’ll be fun!

Question 1: Scope

Consider the following code:

(function() {
   var a = b = 5;
})();

console.log(b);

What will be printed on the console?

Answer

The code above prints 5.

The trick of this question is that in the IIFE there are two assignments but the variable a is declared using the keyword var. What this means is that a is a local variable of the function. On the contrary, b is assigned to the global scope.

The other trick of this question is that it doesn’t use strict mode ('use strict';) inside the function. If strict mode was enabled, the code would raise the error Uncaught ReferenceError: b is not defined. Remember that strict mode requires you to explicitly reference to the global scope if this was the intended behavior. So, you should write:

(function() {
   'use strict';
   var a = window.b = 5;
})();

console.log(b);

Question 2: Create “native” methods

Define a repeatify function on the String object. The function accepts an integer that specifies how many times the string has to be repeated. The function returns the string repeated the number of times specified. For example:

console.log('hello'.repeatify(3));

Should print hellohellohello.

Answer

A possible implementation is shown below:

String.prototype.repeatify = String.prototype.repeatify || function(times) {
   var str = '';

   for (var i = 0; i < times; i++) {
      str += this;
   }

   return str;
};

The question tests the knowledge of the developer about inheritance in JavaScript and the prototype property. It also verifies that the developer is able to extend native data type functionalities (although this should not be done).

Another important point here is to demonstrate that you are aware about how to not override possible already defined functions. This is done by testing that the function didn’t exist before defining your own:

String.prototype.repeatify = String.prototype.repeatify || function(times) {/* code here */};

This technique is particularly useful when you are asked to shim a JavaScript function.

Question 3: Hoisting

What’s the result of executing this code and why.

function test() {
   console.log(a);
   console.log(foo());
   
   var a = 1;
   function foo() {
      return 2;
   }
}

test();

Answer

The result of this code is undefined and 2.

The reason is that both variables and functions are hoisted (moved at the top of the function) but variables don’t retain any assigned value. So, at the time the variable a is printed, it exists in the function (it’s declared) but it’s still undefined. Stated in other words, the code above is equivalent to the following:

function test() {
   var a;
   function foo() {
      return 2;
   }

   console.log(a);
   console.log(foo());
   
   a = 1;
}

test();

Question 4: How this works in JavaScript

What is the result of the following code? Explain your answer.

var fullname = 'John Doe';
var obj = {
   fullname: 'Colin Ihrig',
   prop: {
      fullname: 'Aurelio De Rosa',
      getFullname: function() {
         return this.fullname;
      }
   }
};

console.log(obj.prop.getFullname());

var test = obj.prop.getFullname;

console.log(test());

Answer

The code prints Aurelio De Rosa and John Doe. The reason is that the context of a function, what is referred with the this keyword, in JavaScript depends on how a function is invoked, not how it’s defined.

In the first console.log() call, getFullname() is invoked as a function of the obj.prop object. So, the context refers to the latter and the function returns the fullname property of this object. On the contrary, when getFullname() is assigned to the test variable, the context refers to the global object (window). This happens because test is implicitly set as a property of the global object. For this reason, the function returns the value of a property called fullname of window, which in this case is the one the code set in the first line of the snippet.

Question 5: call() and apply()

Fix the previous question’s issue so that the last console.log() prints Aurelio De Rosa.

Answer

The issue can be fixed by forcing the context of the function using either the call() or the apply() function. If you don’t know them and their difference, I suggest you to read the article What’s the difference between function.call and function.apply?. In the code below I’ll use call() but in this case apply() would produce the same result:

console.log(test.call(obj.prop));

Conclusion

In this article we’ve discussed five typical questions that are asked at interviews to test a JavaScript developer. The actual questions may differ from interview to interview but the concepts and the topics covered are usually pretty similar. I hope you had fun testing your knowledge. In case you didn’t know some of all of the answers, don’t worry: there is nothing that studying and experience can’t fix.

If you have been asked some other interesting questions at interviews, don’t hesitate to share them with us. It’ll help a lot of developers.

  • http://nyasro.com/ Nyasro

    Very nice :)
    Today I learned new thing about Javascript this keyword.

    I liked “this keyword, in JavaScript depends on how a function is invoked, not how it’s defined”.. Nice one :)

    • Tom Hicks

      I’ve done a similar write up of questions I use when testing for javascript ability here: http://tomhicks.github.io/code/2014/09/12/javascript-interview-questions.html

      I don’t cover hoisting explicitly which you do well, but I think I cover the nature of prototypes in more depth.

      I would be interested to hear what kinds of things you do for testing higher level concepts like api design and clean coding as I find those things harder to test for without having to spend a long time doing it. I like that these kinds of tests are quick and pretty accurate.

  • http://jeditux.wordpress.com/ Fernando Basso

    Cool stuff. I have some Anki cards regarding some of the topics covered in the post, like the stuff about the `this` keyword. The tips on this post will end up in my cards as well. Thanks. By the way, well written and clear explanation!

    • Aurelio De Rosa

      Hi Fernando.

      Thank you for the compliments. I’m glad you liked the article and that, hopefully, you’ve learned something new.

    • Ben Henick

      Either I’ve been doing this for too long, or jQuery’s been making devs flabby for too long.

      …But if that means that my JavaScript chops are still okay, that’s a good thing.

      Thanks for going to the trouble to get this article published.

      • compengg

        I am totally new bie for jquery and javascript.

        Can anyone tell me that how the pages are flying out ,one over the other in the following website?

        https://www.navdy.com/?utm_source=AdWords&utm_medium=CPC
        Is this jquery magic or javascript.? what is the terminology for it? flyouts or hovering pages or what?pls reply at

  • Amity Binkert

    Curious about #2 – native methods: What’s the expected behavior of your ‘repeatify’ function If you test that you don’t override a pre-existing version of the function? Is the point that you won’t mess up any other code on the page with the expense of your own code not functioning properly?

  • ShirtlessKirk

    “It also verifies that the developer is able to extend native data type functionalities (although this should not be done).”

    Why not? You should never extend Object.prototype, but there’s nothing wrong with extending String.prototype to implement .trim() where it isn’t supported by the browser.

    What can trip you up, however, is if you go extending happy and add all kinds of proprietary methods just because you can.

    • Aurelio De Rosa

      Because you can never know what other libraries integrated in the project will do. What if projects like jQuery, Underscore, or others decided to add their methods to the prototype of native objects? A project would become a mess and nobody could easily predict the method of what library you are using (are you using jQuery’s trim, Underscore’s trim, a ECMAScript’s trim?). What this means is that you don’t know how many and what are the parameters of the method, the returned values, and so on.

  • http://function.fr/ Vincent Voyer

    Another great exercice is this:


    var items = document.querySelectorAll('.items');
    for (var i = 0, max = items.length; i < max ; i ++) {
    var element = items[i];
    element.addEventListener('click', function() {
    console.log('you clicked on element number ' + i);
    });
    }

    // Given 10 items, what's the output on the console if I click on the third item?
    // Why?
    // How to fix this behavior?

    What do you think?

    • Aurelio De Rosa

      That’s a good exercise too. The concept to solve this is a good understanding of the closure that I’ve discussed in Question 4, but this is another good question to propose.

      • http://function.fr/ Vincent Voyer

        Thanks for reply.

        I found out that nowhere in your article your were talking about closures, nor in question 4.

        Question 4 is about `this` and context. While my exercice is about scope (problem) and closures (solution).

        • http://www.aamirafridi.com/ Aamir Afridi

          I understand the problem but do you mind explaining the solution.

          • http://function.fr/ Vincent Voyer

            So the solution to the problem:


            var items = document.querySelectorAll('.items');
            for (var i = 0, max = items.length; i < max ; i ++) {
            var element = items[i];
            element.addEventListener('click', createLog(i));
            }

            function createLog(i) {
            return function logLocal() {
            console.log('you clicked on element number' + i);
            }
            }

            By calling a function (createLog) that will return a function (logLocal), you are able to reference `i` at the value it had when the loop iterate on it.

            Basically you are creating a new scope where `i` has the value you expect. Not just the last value of the loop.

            As in JavaScript number and strings are copied by value, you get a new var.

            If `i` was an object, you would get a reference to the `i`at the time of the iteration, which is what you want.

            This exercise test the ability of the candidate to understand that a lot of the power of JavaScript comes from the fact that you can have functions creating and returning new functions. Coupled with how scope works, you can have great solutions to common problems.

          • http://harunyasar.ghost.io/ Aaron

            @Vincent, this is a unnecessary detail and the problem was scope. I think mine is cool solution than yours. Check it below…

            var items = document.querySelectorAll('.items');
            for (var i = 0, max = items.length; i < max; i++) {
            (function (n) {
            var element = items[i];
            element.addEventListener('click', function () {
            console.log('you clicked on element number ' + n);
            });
            }(i));
            }

          • Ian

            It will work if capturing every in the loop..

            var items = document.querySelectorAll(‘.items’);
            for (var i = 0, max = items.length; i < max; i++) {
            var element = items[i];
            element.addEventListener('click', (function(n){
            return function () {
            console.log('you clicked on element number ' + n);
            };
            }(n)));
            }

          • http://function.fr/ Vincent Voyer

            It’s a lot less readable than externalizing your closure to a named function.

            I used to write code like this untill I really understood functions in JavaScript

            It does not allows you to transform your closure in a module.

          • http://www.kaffeinelab.com/ Tom

            I don’t think it’s less readable, and we are not talking about reuse the code, in fact to me is more intuitive since demonstrate clousures better ;)

          • Long Huynh

            why not just use .bind()?

          • http://gutweb.co.il Vadim Gutman

            Common guys lets go ECMA 6
            why not just use ‘use strict’;

            and add a ‘let _i = i;’ in the loop

            problem solved

          • WiseFundManager

            I like this approach better:

            ‘use strict’;

            var items = document.querySelectorAll(‘.item’);

            for (var i = 0, max = items.length; i < max; i++) {

            var element = items[i];

            this.response = function (n) {

            console.log('you clicked on element number ' + n);

            };

            element.addEventListener('click', this.response.bind(this, i));

            }

          • Bah-Djibril Alpha

            @harunyasar:disqus I see your solution is actually nicer but the advantage of declaring a function like @vvoyer:disqus did is that you save the performance hit when you have a lot of items. The anonymous function gets declared and then calls itself each time. Declaring it avoids the declaration to happen for each loop.

            Cheers

          • San Jose Sprint ST

            @Aaron While I agree that it puts it all in one place, but Vincent solution separates the 2 functions allowing independent reusable functions where yours is tightly coupled so your methods are locked in to that one functionality.

        • dotDeeka

          Isnt the easiest way to just assign i to a local variable in your callback

          super readable very simple.

    • Aurelio De Rosa

      I think I’ll use it in an upcoming sequel.

    • welbornio

      That’s a great one.

    • http://callmenick.com Nick Salloum

      Great exercise to test closure and run time knowledge!

    • Igor Buts

      Vincent, thanks for good exercice.
      Im I right that using es6 and just changig ‘var’ to ‘let’ in the line2 will solve the problem?

      • http://function.fr/ Vincent Voyer

        Yes!

        See:


        for (let i = 0, max = 9; i < max ; i ++) {
        setTimeout(function() {
        console.log('item is ' + i);
        }, 200);
        }

        • Jesus

          Does it work if I wrap the code inside the for loop inside an IIFE?

          • Paca-vaca

            Yes, because the IIFE creates the closure for each “I”

  • Ronnie_Gardocki

    What about this? (2)
    String.prototype.repeatify = String.prototype.repeatify || function(num) {
    if (isNaN(parseInt(num, 10))) return “sorry, we need a number”;
    return new Array(num+1).join(this);
    }

    • Ed Bespalov

      You should throw an exception instead of return “sorry, we need a number”
      You can’t distinguish correct call:
      “sorry, we need a number”.repeatify(1)
      and incorrect one:
      “sorry, we need a number”.repeatify()

      • Aurelio De Rosa

        I agree, good point.

  • Karol Andrusieczko

    Hey,

    In “How this work in JavaScript”, there’s something a little bit unclear.

    The variable `fullname` is not set as a global one, so if you wrap the whole example in the (function() { // code })(), then, the result will be “Aurelia De Rosa” and `undefined`.

    Nice examples by the way ;)

    • Aurelio De Rosa

      What exactly is unclear? You don’t need to wrap the code inside a function. Even if you use the “var” keyword when you create a variable in the global scope it’s assigned to the “window” object.

      • Karol Andrusieczko

        … and you got me ;) Of course you are right but it’s just tricky. To a js developer who doesn’t write a code in a global scope too often, it can be quite hard to realize that. And the purpose of the exercise was the context :)

        Nevertheless, a good one and everybody should be aware of what you wrote.

      • Alfred

        Assume a novice node developer who is doing your exercises by running them via node. He’ll get Aurelio de Rosa and undefined as a result. So I would say that the example is a bit unclear, indeed. Besides this, thanks for the great & enlightening article :)

  • Aurelio De Rosa

    Ideally you should never assign a function to a native object prototype (as I wrote). In case you do, you should only replicate the behavior of functions that should have been there. So, if such native function doesn’t exist, your replacement should have the behavior of the native function. Doing so, even if you remove your replacement, the code will still work.

  • Jocelyn Lecomte

    Nice little exercises, though the first one is more tricky than hard. I must say I had it wrong, but viewing at the answer, I easily could explain why. So it seems to me that the real problem was not scope, but the var declaration here.

    In the fifth exercise, I expected you to ask:

    Fix the previous question’s issue so that the last console.log() prints Colin Ihrig.

    It makes more sense to me because obj doesn’t have a getFullName() method.

  • http://anagrammatically.com Antonios Sarhanis

    I thought questions 1 and 3 were a little contrived and nasty.

    Really, the answer to question 1 is: never define variables like that.

    Similarly, the answer to question 3: just don’t do it.

    Questions 2, 4 and 5, however, were pretty good ways to ascertain knowledge of Javascript features that are important to know.

  • Jonatan Brown

    Wouldn’t a more elegant solution to the last problem be to use .bind(obj.prop) on the getFullName function?

    • http://bucaran.me Jorge Bucaran

      Certainly. Or just this.

      var fullname = 'John Doe';
      var obj = {
      fullname: 'Colin Ihrig',
      prop: {
      fullname: 'Aurelio De Rosa',
      getFullname: function() {
      return this.fullname;
      }.bind(this)
      }
      };

  • http://glebbahmutov.com/ Gleb Bahmutov

    I prefer to see the candidate first formulate the answer, then write unit tests, then write code that makes the tests pass. Then iterate. This could apply to these questions, but I prefer functional-lite javascript questions because they map naturally to english and to unit tests, see http://bahmutov.calepin.co/functional-javascript-interview-question.html

  • http://ericnjanga.com Eric Njanga

    Great article. Thank you.

    • Aurelio De Rosa

      Hi Eric.
      I’m glad you liked it :)

  • Frederik Krautwald

    Die, JavaScript. Die!

    • Aurelio De Rosa

      Why such hate?

      • Frederik Krautwald

        (function foo() {
        //some stuff
        }());

        (function foo() {
        //some stuff
        })();

        var foo = function () {
        //some stuff
        }();

        var foo = (function () {
        //some stuff
        }());

        var foo = function () {
        // Works!
        }();

        function foo() {
        // SyntaxError: Unexpected token )
        }();

        ;(functions () {
        // Good practice
        }());

        null is an object, but has no properties like object.

        1 == 1; //true
        ‘foo’ == ‘foo’; //true
        [1,2,3] == [1,2,3]; //false

        [] + {}; //[object Object]

        1 + 1 === 1 + 1 //true
        1 + 2 === 2 + 1 //true
        [] + {} === {} + [] //false

        []+(-~{}-~{}-~{}-~{})+(-~{}-~{}); // “42”

        JavaScript, you’re killing me!!!

        • Frederik Krautwald

          Try this in your console:

          Array(16).join(“wat” – 1) + ” Batman!”;

          • Frederik Krautwald

            Watmaan

        • Aurelio De Rosa

          The first example you reported are not the same thing. The syntax is different because you are talking about different concepts: IIFE vs function declarations vs function expressions.

          The other are true in every decent programming language: basic types are compared based on their value, objects based on the reference.

          The last examples should never be written, so there is no point in discussing them.

          • Frederik Krautwald

            “The last examples should never be written, so there is no point in discussing them.”

            – HAHAHAHA… they can be written. They are written. And the language allows them to be written. Yet, you won’t discuss them. Absolutely WATMAN!

          • Aurelio De Rosa

            I challenge you to find an expression like those you mentioned in any serious project like jQuery, Modernizr, or similar. If you want to just blame JavaScript, then you know what Bjarne Stroustrup said?

            “There are only two kinds of languages: the ones people complain about and the ones nobody uses.”

          • Frederik Krautwald

            Come on, take it easy JS lover. It is an awesome but terrible language with many design flaws. How about 0.1 + 0.2?

          • Aurelio De Rosa

            Do you know that you have just demonstrated your poor knowledge of programming languages to the world, right? Do you know that similar issues affect ALL programming languages even more “cool” one like Java? You’d better read this article:

            http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

            Example in PHP:

            // prints 7, not 8
            echo (int) ((0.1 + 0.7) * 10);

          • Frederik Krautwald

            Jaysus!!! My “poor knowledge of programming languages”!!! Are you for feckin’ real? I mention some design flaws and curiosities (even funny ones) in JS, and off you wander into straw man’s land, trying to slander me with an ad hominem attack.

            And so what that both Java, PHP and whatever other languages have their design flaws, too? How is that going to make JavaScript’s shortcomings disappear?

            I think you should go and chill out a bit before you dig yourself any deeper into the world of personal attacks. Peace out, man.

          • http://mlarocca.github.io Marcello La Rocca

            0.1 + 0.2 is not a JavaScript flaw, it is a flaw of the binary floating point notation, basically due (really in a nutshell) to the fact that it uses powers of two and can not accurately represent decimal fractions, while (shoot!) we use right a decimal system, instead.

            Assuming you are not in the mood to read, you can watch this: http://youtu.be/3WgVHE5Augc?t=19m43s
            (Still, you’ll need a tiny bit of patience and watch at least 4 or 5 minutes – but, come on, hang in there: who knows, you might even learn something…)

            So… try again, maybe you’ll be in luck next time ;-)
            After all, there are many real flaws in JS, as there are in Java, C, Haskell (yes, even Haskell!) and basically any language.

          • Guilherme

            Yow know that 0.1 + 0.2 is not a JS flaw, right?

          • Oscar M

            I agree, Frederik if something like this was presented in a project I would assume it came from an intern…

            There are these thinks called conventions and guidelines which developers should follow and when they don’t then unexpected behaviours can occur (this applies to any language and any framework). The point is that yes there are flaws but you avoid them by following the right practices and by doing things as they where intended to be used.

            Also there is really no point in hating programming languages, its just means to an end and currently there are no alternatives (at least not practical one) that you can use so I’m pretty sure it will not die any time soon. I’m aware that some alternatives do exist (like Google’s Dart) but you cannot use them yet (support issue, compatibility issue, etc.).

            Nevertheless Aurelio I really like your questions and those 5 follow ups, they are straightforward and to a point. Please consider making some more because they helped me a lot, also note that I used your questions and some of these web tests (HTML, CSS and JS) for a fast preparation and it turned out great.

          • Frederik Krautwald

            There are these thinks called conventions and guidelines which developers should follow and when they don’t then unexpected behaviours can occur (this applies to any language and any framework).

            Uhm, you are wrong. You don’t need conventions and guidelines to avoid unexpected behaviour in Haskell. In Haskell, adhering to the syntax is all that matters.

      • Frederik Krautwald

        Oh, did I mention…

        [] + {}; // [object Object]

        …but

        {} + []; // 0

        Die, JS!

        • Maksim Vi.

          Why would you do this on a first place?

          • Frederik Krautwald

            To know the quirks of the language.

          • JasonEnzoD

            Because he’s a tester?

    • JasonEnzoD

      Unfortunately, that is not going to happen, because it has become popular, and popularity is what rules. It doesn’t mean to say it’s a good for you. Just like McDonald’s burgers.

      This is why things get dumbed-down. But when you try to dumb-down something that is intrinsically complicated, like a programming language, you end up with the mess that is JavaScript.

      Meanwhile, excellent languages like Java suffer.

  • vomitory

    Please explain, question #4, line 14. Why doesn’t it just crash? I mean, how does the same property getFullName exists in two forms, function and variable? It’s not a quantum mechanics! Ok, let’s say, they co-exist. But how the hell, variable getFullName points to global fullName? There’s no direct reference anywhere! Sorry for exclamation – there’s not other way to ask that…

    • scottseeker

      Because the context in this case is the global context, so ‘this’ refers to the fullName established at the global level.

    • aumi first

      getFullName does not exist in two forms, it exists in one form only and this is the property of `obj.prop`. This property holds a reference to a value and the value is an anonymous function. Why it is anonymous – because it doesn’t have name. And even if it would have some name, e.g.:

      var obj = {
      fullname: ‘Colin Ihrig’,
      prop: {
      fullname: ‘Aurelio De Rosa’,
      getFullname: function SomeName() {
      return this.fullname;
      }
      }
      };

      – even then that name wouldn’t allow us to call this function using that name, because the function is declared in such a way that it went into hidden scope of its own so to say. So there is no other way to reference that part of memory where it is placed other then through ‘getFullname’ property of obj.prop .

      Having said that, when one write at line 15:

      var test = obj.prop.getFullname;

      – one indeed assigns value of property obj.prop.getFullname (which references our anonymous function) to the variable `test`.

      This illustrates the fact that in JS functions are ‘first class objects’ – you can pass them around just like arrays, strings, numbers or any other objects.

      And when you then write: `test()` – what happens? – JS engine first askes itself: What is this `test`? And it answeres to itself: Well, `test` is a variable pointing to such and such anonymous function. Then JS gets that function’s executable code and apply () – to run that code.

  • Jingqi Xie

    A lot easier than what I have faced!

  • jer

    Actually the answer to #1 is incorrect. Since the console.log statement is outside the scope of the anonymous function it throws a ReferenceError: a is not defined. http://jsfiddle.net/Ls51jjmm/9/

    To fix this, include the console.log inside the scope of the function like this:

    (function () {
    ‘use strict’;
    var a = Window.b = 5;
    console.log(a);
    })();

  • Michael Burch

    Actually, when I run the Question 4 code in JSFiddle, it returns Aurelio De Rosa and undefined.

  • Frederik Krautwald

    I really love Crockford. He even mentions the “wat embarrassment” to the JavaScript community. But how lucky it is that we have ClojureScript today.

    • WiseFundManager

      You really need to hating, mister hater.

      • Frederik Krautwald

        Thanks for the labeling roses, how mature of you.

        • WiseFundManager

          you should quit coding, you have the wrong attitude.

      • Frederik Krautwald

        I am not hating, I’m stating the facts. For that very reason we have seen numerous attempts to fix the broken JavaScript, such as Google Closure, TypeScript, and newest kid on the block PureScript. You really need to stop your name calling.

  • Gaurang

    Hi Aurelio De Rosa,

    I had a doubt in question # 4.

    I kept on getting ‘undefined’ for line 16. I used the exact same code. Now my understanding is this is because getFullname looks for fullname value in scope of ‘test’ object but can’t find it. I got the output that you talk about after i removed ‘var’ keywork to make fullname on line # 1 global. Is my understanding correct or am I missing something?

    Thanks
    Gaurang

  • James Brown

    Just FYI. if you are interested in javascript quizzes, i have found a lot them here: http://quizful.com/app

  • Imstillreallybored

    I was confused by question 4 i thought the answer you put down was wrong and it is. The second output is not “John Doe” its undefined.

    http://jsfiddle.net/t4krszpb/

  • Billy J Figueroa

    Good Article, these are the types of things you learn in books like ‘Secrets of the JavaScript Ninja”.

    Thanks for the article. @vvoyer:disqus good stuff too. I have seen the IIFE used and passed i the way @harunyasar:disqus is doing it. I don’t think it over complicates things. I am not a big fan of functions inside of functions lol that confuses me more than seeing a IIFE being passed i as a param

  • Al

    All these questions were asked to me as-is in my yesterday’s front end UI dev role.

  • Vitor Canova

    Damn. I’m fired.

  • http://ecomspark.com/ K Gaurav

    Great learning here..thanks..:)

  • Serhii Pahuta

    String.prototype.repeatify = function(t) {
    return (new Array(t+1)).join(this);
    }

  • samala shivateja

    How to find out factors of a number in the same page using javascript ?
    I used the below program ,got result but the past results are not vanishing when input changes. Any one help me.

    Factors

    function main(){

    var x = document.getElementById(“userInput”).value;

    for (var i=1;i<=x;i++){

    if (x % i == 0){

    document.getElementById('my-output').innerHTML+= +i+',';

    }

    }

    };

    The factors of the number:

  • Praveen Gupta

    Keyword is variable hoisting. As control enters function foo, it finds all var declarations and declares those. On execution if statement does not get executed. It is executed as if function foo is defined as follows:

    function foo() {
    var x;

    if(false) { //never executes
    x = 99;
    }

    console.log(x); //undefined
    }

    Hope this helps.

  • Oziel Perez

    For gods sakes, I can never finish learning javascript -____-

  • tyler

    Thank you for this article. I’m just getting in to javascript as I am a UX designer and this skill will help me communicate with developers and create my own projects.

  • http://yongyuan.us 哥特复兴

    so easy

  • mohit baveja

    var fullname = ‘John Doe’;
    var obj = {
    fullname: ‘Colin Ihrig’,
    prop: {
    fullname: ‘Aurelio De Rosa’,
    getFullname: function() {
    return this.fullname;
    }
    }
    };

    console.log(obj.prop.getFullname());

    var test = obj.prop.getFullname;

    console.log(test());

    prints Aurelio De Rosa and undefined.

    console.log(test()); doesn’t print John Doe in above example

    • Aurelio De Rosa

      Not true. It does print what the article states.

  • bealeck

    need to pass the argument into the IEFF function too :)
    (function ( ) {
    should be
    (function ( i ) {

  • supersonicecho

    I think there is a mistake in the answer for Question 4.

    I believe the correct answer is “Aurelio De Rosa” and “undefined” (in non-strict mode). fullname is not a property of the window object because it was declared with the var keyword. If the var was left out, then it would be implicitly defined as a property of the window object (in non-strict mode).

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.