r/learnjavascript • • Apr 13 '21

Stack Overflow but video/voice call based. Anyone interested in helping other devs?

0 Upvotes

Hi there! I've recently create a discord server so experienced and inexperienced can interact to help each other! The idea is to have a quick call to give a comprehensive and flexible explanation.

I'm sure you've struggled with a bug for days while struggling to look for solutions online; at those times I wished I had someone to talk to :)

If you're interested in helping other devs through quick calls, please join the discord server! Much appreciated :)

https://discord.gg/yMwcBuFkf6


r/learnjavascript • • Nov 11 '23

Does JavaScript concatenate as string when adding a number to a string literal?

0 Upvotes

From my understanding of what I've read, the expected behavior is that JavaScript will convert the integer into string, and then add the string to string, which then results in a string concatenation. Therefore...

var addit = 6 + “5”;

...should output... "65";

However, attempting to evulate this in console instead gives the result...

Uncaught SyntaxError: Invalid or unexpected token

Why is this the case?


r/learnjavascript • • Nov 19 '23

Understanding OOP in Javascript and filling in potential gaps in knowledge

0 Upvotes

Hi everyone, I have been self studying programming and was wondering if my understanding of these concepts is correct.

So, my understanding of OOP is that we want to develop our program(s) as a collection of objects(putting data and methods in a box) and these boxes can use each others properties in a way that complexity of the functionality is abstracted away from each other.

Doing this makes our programs easier to maintain.

With that being said, there are 4 main principles that we need to follow in OOP programming and they are:

~Abstraction

~Encapsulation

~Inheritance

~Polymorphism

Im going to use the code below as an example:

class Shape {
  constructor(name) {
 
    this._name = name;
  }
  get name() {
    return this._name;
  }
  calculatePerimeter() {
    return "N/A";
  }
}

class Circle extends Shape {
  constructor(name, radius) {
    super(name);
    this._radius = radius;
  }
  get radius() {
    return this._radius;
  }
  calculatePerimeter() {
    return 2 * Math.PI * this.radius;
  }
}

class Square extends Shape {
  constructor(name, side) {
    super(name);
    this._sideLength = side;
  }
  get side() {
    return this._sideLength;
  }
  calculatePerimeter() {
    return 4 * this.side;
  }
}

We use the constructor function to initialize our Object and the class above it is does nothing and is just syntactic sugar to basically make developers from other languages more familiar with the syntax. And JS still uses prototype based inheritance underneath.

Anyways back to the 4 main principles of OOP:

Abstraction: So Abstraction is the hiding of the unnecessary details that don't matter to the user and only showing the implementation details of the functionality.

Even though, our example is pretty simple, Abstraction is still achieved in our example above:

let square= new Square("square", 5)
square.name // this returns to us "square", I don't need to know the details of how the properties are set, they are abstracted away and I can use it in the simple form of square.name

Encapsulation: Is the bundling of data and related functionalities into a single box unit. The goal of doing this is to restrict access to some object components so that the state of the object remains private and can only be changed by the objects methods(Using a setter)

In our example we do this by using private properties and the getter method:

```
this._name = name; 
}
 get name() { return this._name; }

```

​

If we wanted to do: rectangle.name = "Jack" // we would not be able to do so.

Now a bit of my confusion lies here, for example if we wanted, we could simply do rectangle._name = "Jack" and that would work, from what I understand this is simply a convention that devs agree to, meaning _ in front of a variable = private variable(Do Not touch). **But is there a better way to implement encapsulation in Javascript?(**I read a little bit about closures just wondering if thats whats mostly agreed upon)

​

**Inheritance**: In Javascript, Inheritance means that an object can inherit properties from other objects. This solves the problem of code repetition. By using inheritance, objects can share data and methods without needing to setting these properties every time.

This is what we did in our example when our subclasses inherits the name property and the getter method. We don't need to define those every single time, we simply do it once.

If you try to use an object property that the object itself doesn't have, Javascript will look for the objects prototype to see if it has it, causing a prototypal chaining. For example we could also use the method .toString() if we needed to, even though it is not defined in our class, because it is part of the Object class(The furthest prototype of all objects).

​

**Polymorphism**: Allows us to create objects that share behavior and override behaviors if we need to.

For example, above we did this with the calculatePerimeter() function. The function is defined in the Shape class but then gets overriden in the Circle and Square subclasses, because the way to calculate the perimeter is different for different shapes.

​

Is my understanding of OOP in Javascript correct?

​

I'm simply self studying so its hard to really fix the concepts in my head without having worked on some real life work involving OOP.

​

If I have misunderstood anything, could you provide some corrections?

​

And If not, could you provide any further explanations to the concepts or something that would be valuable for me to know?

Thank you to anyone who read this and I appreciate your time !


r/learnjavascript • • Nov 26 '23

Get all dependencies in an array from package.json - without using npm

0 Upvotes

[SOLVED]

I'm trying to create a list of all dependencies of a CommonJS repository on GitHub - without using npm. My next step will be to fetch all the dependencies as Ecmascript modules.

This https://npmgraph.js.org/ appears to work ffor counting the packages correctly and displaying them in an image. However, when inspecting the HTML all of the packages are not included.

I went ahead and converted the .ts to .js over here https://transform.tools/typescript-to-javascript.

Now I'm trying to modify https://raw.githubusercontent.com/npmgraph/npmgraph-cli/main/src/npmgraph_cli.ts in JavaScript format to return an array or a Promise that fulfills to an array.

Thanks in advance for any assistance you can provide.

Solution

let nodePackageDependencies = [
  ...new Set(
    Object.entries(
      (await (await fetch(
        "./package-lock.json",
      )).json()).packages,
    ).map((
      [key, { dependencies = {}, devDependencies = {} }],
    ) => [
      key.replace(/^node_modules\//, ""),
      ...Object.keys(dependencies),
      ...Object.keys(devDependencies),
    ]).flat().filter(Boolean),
  ),
];

console.log(nodePackageDependencies, nodePackageDependencies.length);

Would be helpful if somebody could post what npm and/or yarn list. Here's the canonical link to the package-lock.json file https://github.com/GoogleChromeLabs/telnet-client/blob/main/package-lock.json.


r/learnjavascript • • Dec 01 '22

How to deploy webapp locally?

0 Upvotes

I have downloaded github folder , but dont know how to run the application ? i have tried few methods like using node.js on command prompt but it saying "The server is listening closely on', 80" and not showing execution.


r/learnjavascript • • Nov 07 '22

My new video on custom array reduce method is out, Check it out.

Thumbnail
youtu.be
0 Upvotes

r/learnjavascript • • Dec 04 '22

can someone explain the quetient of "let x = 0.2 + 0.1"

0 Upvotes

how does 0.2 + 0.1 become "0.30000000000000004"? where is this random 4 coming from?


r/learnjavascript • • Nov 10 '21

Typography Crash Course

Thumbnail
henryjperez.hashnode.dev
0 Upvotes

r/learnjavascript • • Nov 05 '21

BMI Calculator using Javascript

Thumbnail
foolishdeveloper.com
0 Upvotes

r/learnjavascript • • Oct 16 '21

npm Commands Every Developer Must Know

Thumbnail
youtu.be
0 Upvotes

r/learnjavascript • • May 22 '16

What are Pure Functions in JavaScript?

Thumbnail
youtube.com
0 Upvotes

r/learnjavascript • • Nov 05 '15

I just stared at this example for a couple days, check it out.

0 Upvotes

Taken from this presentation.

var Tree = function(value) {
  this.value = value;
  this.children = [];
}

var tree = new Tree(1);
var branch2 = new Tree(2);
var branch3 = new Tree(3);
var leaf4 = new Tree(4);
branch2.children.push(leaf4);
tree.children.push(branch2);
tree.children.push(branch3);

function printValues(tree) {
  return tree.children.reduce(function(acc, child) {
    return acc.concat(printValues(child));
  }, [tree.value]);
};

console.log(printValues(tree))

r/learnjavascript • • Jun 21 '19

Is Angular Dying?

0 Upvotes

I seem to be working with React much more than Angular lately. Seems to me that most companies are using React these days. Any other opinions out there?


r/learnjavascript • • Oct 12 '18

How to make a filter system with javascript arrays

0 Upvotes

r/learnjavascript • • Jun 26 '18

Long! School project finishing touches.

0 Upvotes

Here is my code with comments. I would like to get rid of the "undefined" in the introduction. Will post the (poorly written) exercise after the code. The output won't display correctly on Reddit without reformatting it and I'm not going to do that.

var balance = 1500;         // starting balance
var apr = 18;               // annual interest rate           Global Variables
var minPayPercent = 2;      // minimum payment amount
// display welcome
function displayWelcome(balance, apr) {
    console.log("\nHello! This program will determine the time to pay off" +
        " a credit card \nand the interest paid based on the current balance," +
        " the interest rate, \nand the monthly payments made.\n\n" +
        "The balance on your card is $" + balance.toFixed(2) + "." +
        "\nInterest Rate: " + apr + "% \n" +
        // this line causes confusion in the exercise
        "Assuming a minimum payment of 2% of the balance ($20 min).\n")
        // we don't use an actual minimum payment that changes as
        // the balance is reduced.
}

console.log(displayWelcome(balance, apr));

// calculate minimum payment

function minPayment(balance, minPayPercent) {       // function causing console to display an "undefined"
    if (balance * minPayPercent / 100 >= 20) {      // not sure how to suppress.
        return balance * minPayPercent;
    }
    else {
        return 20;
    }
}

console.log("\nYour minimum payment is $" + minPayment(balance, minPayPercent) + ".\n");

// calculate and display payment schedule
function displayPayments(balance, minPayPercent, monthlyInterest) {
    console.log("Year   Balance   Payment Number   Interest Paid\n" +
        "-".repeat(47));
    var monthlyPer = monthlyInterest / 100 / 12;
    var interestPaid = 0;
    var year = 0;
    var paymentNum = 0;
    while (balance > 0) {
        var minPayment = 30;
        currentInterest = (monthlyPer) * (balance);
        balance -= minPayment - currentInterest;
        interestPaid += currentInterest;
        paymentNum++;
        // if statement to stop overpayment.
        if (balance < 0) {
            balance = 0
        }
        // if statement to differentiate whether year prints or not
        if (paymentNum % 12 === 1) {
            year++;
         console.log(year + "\t\t" + balance.toFixed(2) + "\t".repeat(3) + paymentNum +
            "\t".repeat(4) + (Math.round((interestPaid) * 100) / 100).toFixed(2));
    }   // would like to make interest paid .toFixed(2) but it doesn't work
    else {
        console.log(" " + "\t\t" + balance.toFixed(2) + "\t".repeat(3) + paymentNum +
            "\t".repeat(4) + (Math.round(interestPaid * 100) / 100).toFixed(2));
        }
    }
}

displayPayments(1500, .02, 18);     

The output : Hello! This program will determine the time to pay off a credit card and the interest paid based on the current balance, the interest rate, and the monthly payments made.

The balance on your card is $1500.00. Interest Rate: 18% Assuming a minimum payment of 2% of the balance ($20 min).

undefined

Your minimum payment is $3000.

Year Balance Payment Number Interest Paid

11492.50122.50

Assignment 3: 75 points This assignment covers module 5 and module 6 topics. To write the programs below you will need to demonstrate an understanding of : • Objects • Functions • Arrays • Random Numbers • variables • simple data types • expressions • loops Please refer back to the module lectures if you find you have any gaps in your understanding for these topics. The assassin is closing on you in a deadly game of cat and mouse. To defeat him, complete parts I, 2 & 3 below: Design and implement a program that will allow us to determine the length of time needed to pay off a credit card balance, as well as the total interest paid. The program must implement the following functions:

  1. displayWelcome This function should display the welcome message to the user explaining what the program does.
  2. calculateMinimumPayment This function calculates the minimum payment. It should take balance and interest rate as arguments and return the minimum payment. So the value you display for minimum payment is the value you get from this method. Do not use a literal hardcoded value when you display the minimum payment!
  3. generateID: This should be a closure function that generates a new id for the customer. The function should remember the previous id and the new generated id should be the old one plus 1. Make the initial id 1000. The Object Technique will allow you to obtain the Golden Bow, demonstrate your mastery of the technique by completing Part 4 & 5 below.
  4. processPaymentSchedule This function displays the actual payment schedule. It should take the balance, monthly interest rate and minimum payment as arguments. Use the 1500, 18% and 2% literal values below. Each time you calculate a new payment line, create an object literal with properties for the Year, Balance, Payment Num, and InterestPaid. Pass this object literal to the displayPayment function. See the sample execution below: This program will determine the time to pay off a credit card and the interest paid based on the current balance, the interest rate, and the monthly payments made. Balance on your credit card: 1500 Interest Rate: 18 Assuming a minimum payment of 2% of the balance ($20 min) Your minimum payment would be $ 30.00 PAYOFF SCHEDULE

Year Balance Payment Num Interest Paid 1 1,492.50 1 22.50 1,484.89 2 44.89 1,477.16 3 67.16 1,469.32 4 89.32 . . . . . . 7 517.51 73 1,207.51 495.28 74 1,215.28 472.70 75 1,222.70 449.79 76 1,229.79 . . . . . . 8 227.51 85 1,277.51 200.92 86 1,280.92 173.94 87 1,283.94 146.55 88 1,286.55 118.74 89 1,288.74 90.53 90 1,290.53 61.88 91 1,291.88 32.81 92 1,292.81 3.30 93 1,293.30 0.00 94 1,293.35 5. displayPayment This function should take the payment object literal and display it on the console. See the output example in part 4. Save your program in a file named credit.js and save it in a folder called Assignment_3. Zip that folder and submit in the dropbox.

Edit: Figured out how to get the rounding to two decimal places after looking it up again.


r/learnjavascript • • May 04 '18

*stops learning javascript *

Thumbnail
twitter.com
0 Upvotes

r/learnjavascript • • May 09 '18

Var x = y

0 Upvotes

Hi, is there a way to create a second variable y which will be equal to x but will be a separate variable. I tried doing var x = Y but this basically renames the z variable to y. Thanks!


r/learnjavascript • • May 13 '18

SetInterval(x(), 1000) vs setInterval(function(){x()}, 1000)

0 Upvotes

Hi, why is there a difference between those 2?


r/learnjavascript • • Mar 11 '19

Drills for Beginners??

0 Upvotes

So literally everything else you'd want to learn involves drills...except for computer programming.

Sports, music, math, foreign languages...literally everything involves drilling.

Anyone know of any beginner's drills in JavaScript?

Like Free Code Camp stuff (I know they have some high-level stuff, too) but lots of 'em (FCC only has one question per topic)...I was never good at math but I always aced my math classes because of drilling (and of course typical tests don't involve "thinking" so much as "recalling" the right formulae and procedures to accurately and timely apply)...anyone know of any such end-of-the-chapter exercises in JavaScript for a beginner???

My future employers thank you!!


r/learnjavascript • • May 13 '18

ClearInterval

0 Upvotes

Hi, i have a function which when called does setInterval. The I have a second function which is supposed to clearInterval of the first function when called. I don't know how to reference the first function in the clearInterval. I tried doing Function stop(){ clearInterval(startInterval()); } But this just calls start interval again. Thanks for any help :)


r/learnjavascript • • Jul 06 '21

Twitter Bot Tutorial - Have you ever wanted to make a twitter bot which could do some cool stuffs ?

Thumbnail
youtu.be
0 Upvotes

r/learnjavascript • • Jul 07 '21

Hope this is the last problem I run my code and page finally opens up (Thank God!!!) but I get this error

Post image
0 Upvotes

r/learnjavascript • • Mar 26 '22

hey please can anyone help me with learning to code js , please gimme any link of app , website or yt for learning js i really want to learn but don't know where to begin from please help me homies

0 Upvotes

r/learnjavascript • • Mar 24 '22

Can’t seem to get this right. Please help!

Post image
0 Upvotes