How to sum all the digits of a given number in JavaScript

preview_player
Показать описание
#javascript #javascriptexample
Sum of the digits of a given number

JavaScript quick tips

JavaScript Classes Shorts

JavaScript Objects

JavaScript Fetch API TUTORIALS

An Example of JavaScript ...

JavaScript Classes

JavaScript Arrays

JSON

JavaScript vs CSS

100 SHORTS TO START LEARNING WEB DEVELOPMENT

JAVASCRIPT LONGS

JAVASCRIPT FOR BEGINNERS

Javascript Challenge; first to know wins

Javascript Arrays Shorts

Javascript ... Spread and ... Rest Operators

HTML SHORTS FOR BEGINNERS

Table (HTML, CSS, Bootstrap, Javascript, jQuery)

Javascript Clean Code

Visual Studio Code Shorts

Bootstrap Shorts

Long Tutorials HTML CSS JAVASCRIPT AND JQUERY

Jquery Shorts

HTML shorts

JavaScript Shorts

CSS Shorts

Developer Console playlist

Рекомендации по теме
Комментарии
Автор

Interesting!
Also, you could mention another approach to the problem without using String methods (however, the String method is far more efficient when dealing with large numbers, and vice versa while the loop approach is better for small numbers like 15, 124):

function sumDigit(num){ const digits = []; while (num !== 0){ dig = num % 10; num = Math.floor(num / 10) | 0; digits.push(dig);} return digits.reduce((a, b) => a + b, 0); }

Recursion: function sumDigit(n, k){ let digits = [...n.toString()].map(e => parseInt(e)); return k === digits.length ? 0 : sumDigit(n, k + 1);

Also, we can use a function instead of using "+" as in this example: function sum(a, b){ return b === 0 ? a : sum(a ^ b, (a & b) << 1); }
However, if you tell me that this is a bad practice, you will be definitely right! But for learning why not. Keep it up, sir!

sergeiivanov